coralogix-cli 0.1.5

Coralogix CLI - the observability backbone for AI agents and engineering teams.
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
use std::ffi::OsStr;
use std::path::PathBuf;

use anyhow::{bail, Result};
use clap::parser::ValueSource;
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use clap_complete::aot::Shell;
use clap_complete::engine::ArgValueCompleter;
use clap_complete::env::CompleteEnv;
use clap_complete::CompletionCandidate;
use config::OutputFormat;

use coralogix_cli::banner;
use coralogix_cli::commands;
use coralogix_cli::commands::dataprime::DataprimeFilter;
use coralogix_cli::config;
use coralogix_cli::execution::build_targets;
use coralogix_cli::safety;
use coralogix_cli::safety::confirm_destructive;
use coralogix_cli::Tier;

/// Returns profile names from `~/.cx/profiles/` as completion candidates.
fn complete_profile_names(current: &OsStr) -> Vec<CompletionCandidate> {
    let prefix = current.to_str().unwrap_or("");
    config::list_profile_names()
        .unwrap_or_default()
        .into_iter()
        .filter(|name| name.starts_with(prefix))
        .map(CompletionCandidate::new)
        .collect()
}

/// How `search-fields` searches: by semantic description or by value content.
#[derive(Debug, Clone, ValueEnum, Default)]
pub enum SearchType {
    /// Semantic / description-based field search (default).
    #[default]
    Semantic,
    /// Search for fields by value content.
    Value,
}

/// Dataset for `search-fields`. `all` is only valid with `--search-type value`.
#[derive(Debug, Clone, ValueEnum)]
pub enum SearchByValueDataset {
    Logs,
    Spans,
    All,
}

/// Coralogix CLI - the observability backbone for AI agents and engineering teams.
#[derive(Parser)]
#[command(
    name = "cx",
    version,
    about,
    long_about = None,
    help_template = "{before-help}{about-with-newline}\nUsage: {usage}{after-help}\n\nOptions:\n{options}",
    after_help = "\
Query:
  logs               Query logs using DataPrime syntax
  spans              Query spans using DataPrime syntax
  metrics            Query metrics using PromQL
  dataprime          DataPrime language reference and raw queries
  search-fields      Search log/span fields by description or value content

Observe:
  dashboards         Manage dashboards and dashboard folders
  views              Manage saved views and view folders
  slos               Manage SLO definitions

Detect & Respond:
  alerts             Manage alert definitions and suppression rules
  incidents          Manage and triage incidents

Notifications:
  notifications      Manage connectors, routers, presets, and notification testing
  webhooks           Manage outgoing webhooks and automation actions

Data Pipeline:
  parsing-rules      Manage log parsing rules
  enrichments        Manage enrichment rules and custom enrichment tables
  e2m                Manage Events2Metrics definitions
  recording-rules    Manage Prometheus recording rule groups

Cost & Storage:
  usage              View data usage and consumption metrics
  tco                Manage TCO policies and settings
  retentions         Manage data retention settings
  archive (risky)    Manage data archive storage configuration

Integrations:
  integrations       Manage integrations, extensions, and contextual data

Access:
  iam (risky)        Manage API keys, roles, scopes, users, groups, and IP access

Agent:
  schema             Output the full command tree as JSON for agent consumption
  olly               Interact with the AI assistant

Local:
  profiles           Manage profiles (list, add, delete, set-default)
  cleanup            Remove stale temp files"
)]
struct Cli {
    /// Profile(s) to use. Repeat to fan out across multiple profiles simultaneously.
    /// Overrides the default profile set in config.
    #[arg(long, short = 'p', global = true, env = "CX_PROFILE", add = ArgValueCompleter::new(complete_profile_names))]
    profile: Vec<String>,

    /// Coralogix API key (overrides a single profile; incompatible with multiple --profile).
    #[arg(long, global = true, env = "CX_API_KEY")]
    api_key: Option<String>,

    /// Coralogix region (overrides a single profile; incompatible with multiple --profile).
    #[arg(long, global = true, env = "CX_REGION")]
    region: Option<String>,

    /// Output format: text, json, or agents. Overrides the default set in config.
    #[arg(long, short = 'o', global = true)]
    output: Option<OutputFormat>,

    /// Skip confirmation prompts for destructive operations.
    #[arg(long, global = true)]
    yes: bool,

    /// Block all write operations. Useful for safe agent/automation access.
    #[arg(long, global = true)]
    read_only: bool,

    #[command(subcommand)]
    command: Commands,
}

/// Separate CLI parser for the `profiles` command - no global API flags.
#[derive(Parser)]
#[command(
    name = "cx",
    version,
    about = "Coralogix CLI - the observability backbone for AI agents and engineering teams."
)]
struct ProfilesCli {
    #[command(subcommand)]
    command: ProfilesTopLevel,
}

#[derive(Subcommand)]
enum ProfilesTopLevel {
    /// Manage profiles (list, add, delete, set-default).
    Profiles {
        #[command(subcommand)]
        cmd: ProfilesCmd,
    },
}

#[derive(Subcommand)]
enum CompletionsCmd {
    /// Print a completion script to stdout.
    ///
    /// Pipe to a file to install manually, or use `cx completions install` to
    /// let cx choose a default path and track it for future refreshes.
    #[command(after_help = "\
Examples:
  cx completions generate zsh > ~/.zfunc/_cx
  cx completions generate bash > ~/.local/share/bash-completion/completions/cx
  cx completions generate fish > ~/.config/fish/completions/cx.fish")]
    Generate {
        /// Shell to generate completions for.
        shell: Shell,
    },
    /// Install a completion script to a standard path and register it for refresh.
    ///
    /// Default install paths:
    ///   zsh:   ~/.zfunc/_cx
    ///   bash:  ~/.local/share/bash-completion/completions/cx
    ///   fish:  ~/.config/fish/completions/cx.fish
    #[command(after_help = "\
Examples:
  cx completions install zsh
  cx completions install bash
  cx completions install zsh --path /usr/local/share/zsh/site-functions/_cx")]
    Install {
        /// Shell to install completions for.
        shell: Shell,
        /// Override the default install path.
        #[arg(long)]
        path: Option<PathBuf>,
    },
    /// Regenerate all completion scripts previously installed by cx.
    Refresh,
}

#[derive(Subcommand)]
enum Commands {
    /// Manage profiles (list, add, delete, set-default).
    Profiles {
        #[command(subcommand)]
        cmd: ProfilesCmd,
    },

    /// Generate, install, or refresh shell completion scripts.
    Completions {
        #[command(subcommand)]
        cmd: CompletionsCmd,
    },

    /// Remove stale cx_results* files (older than 30 minutes) from the temp directory.
    Cleanup,

    /// Query logs using DataPrime syntax.
    #[command(after_help = "\
Examples:
  cx logs 'filter $m.severity == ERROR'
  cx logs 'filter $d.message ~ \"timeout\"' --start now-6h --tier archive
  cx logs 'filter $l.applicationname == \"api\"' --limit 200 -o json")]
    Logs {
        /// DataPrime query string. e.g. 'filter $m.severity == ERROR'
        query: String,

        /// Start time in ISO 8601 or relative format. e.g. "2024-01-01T00:00:00Z" or "now-1h"
        #[arg(long, default_value = "now-1h")]
        start: String,

        /// End time in ISO 8601 or relative format.
        #[arg(long, default_value = "now")]
        end: String,

        /// Maximum number of results.
        #[arg(long, default_value_t = 100)]
        limit: u32,

        /// Storage tier to search. Overrides the profile's default_tier setting.
        /// If neither is set, defaults to archive.
        #[arg(long)]
        tier: Option<Tier>,
    },

    /// Query metrics using PromQL.
    Metrics {
        #[command(subcommand)]
        cmd: MetricsCmd,
    },

    /// Query spans using DataPrime syntax.
    #[command(after_help = "\
Examples:
  cx spans 'filter $d.traceID == \"abc123\"'
  cx spans 'filter $l.serviceName == \"checkout\"' --start now-2h --limit 50
  cx spans 'groupby $l.operationName aggregate avg($m.duration) as avg_latency'
  cx spans 'filter $m.duration > 1000000' --tier archive -o json")]
    Spans {
        /// DataPrime query string. 'source spans' is automatically prepended if not present.
        query: String,

        /// Start time in ISO 8601 or relative format. e.g. "2024-01-01T00:00:00Z" or "now-1h"
        #[arg(long, default_value = "now-1h")]
        start: String,

        /// End time in ISO 8601 or relative format.
        #[arg(long, default_value = "now")]
        end: String,

        /// Maximum number of results.
        #[arg(long, default_value_t = 200)]
        limit: u32,

        /// Storage tier to search. Overrides the profile's default_tier setting.
        /// If neither is set, defaults to archive.
        #[arg(long)]
        tier: Option<Tier>,
    },

    /// Manage and inspect dashboards.
    Dashboards {
        #[command(subcommand)]
        cmd: DashboardsCmd,
    },

    /// Manage alert definitions and suppression rules.
    Alerts {
        #[command(subcommand)]
        cmd: AlertsCmd,
    },

    /// Manage and triage incidents.
    #[command(after_help = "\
Examples:
  cx incidents list
  cx incidents list --severity CRITICAL
  cx incidents get <incident-id>
  cx incidents acknowledge <id1> <id2>
  cx incidents resolve <id>")]
    Incidents {
        #[command(subcommand)]
        cmd: IncidentsCmd,
    },

    /// Manage connectors, routers, presets, and notification testing.
    #[command(after_help = "\
Examples:
  cx notifications connectors list
  cx notifications routers list
  cx notifications presets list
  cx notifications test connector --from-file test.json")]
    Notifications {
        #[command(subcommand)]
        cmd: NotificationsCmd,
    },

    /// View data usage and consumption metrics.
    #[command(
        name = "usage",
        after_help = "\
Examples:
  cx usage summary
  cx usage daily --type processed-gbs
  cx usage logs-count
  cx usage spans-count"
    )]
    DataUsage {
        #[command(subcommand)]
        cmd: DataUsageCmd,
    },

    /// Manage TCO (Total Cost of Ownership) policies.
    #[command(
        name = "tco",
        after_help = "\
Examples:
  cx tco list
  cx tco get <policy-id>
  cx tco create --from-file policy.json
  cx tco settings"
    )]
    TcoPolicies {
        #[command(subcommand)]
        cmd: TcoPoliciesCmd,
    },

    /// Manage data retention settings.
    #[command(after_help = "\
Examples:
  cx retentions list
  cx retentions status
  cx retentions update --from-file retentions.json")]
    Retentions {
        #[command(subcommand)]
        cmd: RetentionsCmd,
    },

    /// Manage Events2Metrics definitions.
    #[command(after_help = "\
Examples:
  cx e2m list
  cx e2m get <e2m-id>
  cx e2m create --from-file e2m.json
  cx e2m update --from-file e2m.json
  cx e2m delete <e2m-id>
  cx e2m labels-cardinality
  cx e2m limits")]
    E2m {
        #[command(subcommand)]
        cmd: E2mCmd,
    },

    /// Manage Prometheus recording rule groups.
    #[command(after_help = "\
Examples:
  cx recording-rules list
  cx recording-rules get <group-id>
  cx recording-rules create --from-file rules.json
  cx recording-rules update --from-file rules.json <group-id>
  cx recording-rules delete <group-id>")]
    RecordingRules {
        #[command(subcommand)]
        cmd: RecordingRulesCmd,
    },

    /// Manage log parsing rules.
    #[command(
        name = "parsing-rules",
        after_help = "\
Examples:
  cx parsing-rules list
  cx parsing-rules get <group-id>
  cx parsing-rules create --from-file group.json
  cx parsing-rules update --from-file group.json <group-id>
  cx parsing-rules delete <group-id>
  cx parsing-rules usage-limits"
    )]
    ParsingRules {
        #[command(subcommand)]
        cmd: ParsingRulesCmd,
    },

    /// Manage enrichment rules and custom enrichment tables.
    #[command(after_help = "\
Examples:
  cx enrichments list
  cx enrichments add --from-file enrichments.json
  cx enrichments limit
  cx enrichments settings
  cx enrichments custom list")]
    Enrichments {
        #[command(subcommand)]
        cmd: EnrichmentsCmd,
    },

    /// Manage integrations, extensions, and contextual data.
    #[command(after_help = "\
Examples:
  cx integrations list
  cx integrations get <id>
  cx integrations extensions list
  cx integrations contextual-data list")]
    Integrations {
        #[command(subcommand)]
        cmd: IntegrationsCmd,
    },

    /// Manage outgoing webhooks and automation actions.
    #[command(after_help = "\
Examples:
  cx webhooks list
  cx webhooks get <id>
  cx webhooks types
  cx webhooks actions list")]
    Webhooks {
        #[command(subcommand)]
        cmd: WebhooksCmd,
    },

    /// Manage saved views and view folders.
    #[command(after_help = "\
Examples:
  cx views list
  cx views get <id>
  cx views folders list
  cx views folders get <id>")]
    Views {
        #[command(subcommand)]
        cmd: ViewsCmd,
    },

    /// Manage API keys, roles, scopes, users, groups, and IP access.
    #[command(after_help = "\
Examples:
  cx iam api-keys list
  cx iam roles list
  cx iam scopes list
  cx iam users search
  cx iam groups list
  cx iam ip-access get")]
    Iam {
        #[command(subcommand)]
        cmd: IamCmd,
    },

    /// Manage data archive storage configuration.
    #[command(
        name = "archive",
        after_help = "\
Examples:
  cx archive metrics get
  cx archive logs get"
    )]
    DataArchive {
        #[command(subcommand)]
        cmd: DataArchiveCmd,
    },

    /// Manage SLO definitions.
    #[command(after_help = "\
Examples:
  cx slos list
  cx slos get <slo-id>
  cx slos create --from-file slo.json
  cx slos update --from-file slo.json
  cx slos delete <slo-id>")]
    Slos {
        #[command(subcommand)]
        cmd: SlosCmd,
    },

    /// Search log/span fields by description or by value content.
    #[command(after_help = "\
Examples:
  cx search-fields \"http response status code\"
  cx search-fields \"error severity level\" --dataset spans --limit 10
  cx search-fields \"payment\" -s value --dataset logs
  cx search-fields \"kubernetes pod\" -s value --dataset all --limit 20 --offset 10")]
    SearchFields {
        /// Description or value to search for.
        text: String,

        /// Search type: semantic (description-based, default) or value (by field value content).
        #[arg(short = 's', long, default_value = "semantic")]
        search_type: SearchType,

        /// Dataset to search: logs or spans (semantic); logs, spans, or all (value).
        #[arg(long, default_value = "logs")]
        dataset: SearchByValueDataset,

        /// Maximum number of results to return.
        #[arg(long, default_value_t = 10)]
        limit: u32,

        /// Number of results to skip for pagination (only used with -s value).
        #[arg(long, default_value_t = 0)]
        offset: u32,
    },

    /// DataPrime language reference and documentation.
    Dataprime {
        #[command(subcommand)]
        cmd: DataprimeCmd,
    },

    /// Output the full command tree as JSON for agent consumption.
    Schema,

    /// Interact with the AI assistant (single-profile only).
    #[command(after_help = "\
Examples:
  cx olly ask \"What alerts fired today?\"
  cx olly ask \"Show me error logs\" --chat-id <id>
  cx olly ask \"Analyze this metric\" --model claude-sonnet-4-5
  cx olly artifacts get <artifact-id>")]
    Olly {
        #[command(subcommand)]
        cmd: OllyCmd,
    },
}

impl Commands {
    fn is_risky(&self) -> bool {
        matches!(self, Self::Iam { .. } | Self::DataArchive { .. })
    }

    fn is_olly(&self) -> bool {
        match self {
            Self::Olly { cmd } => matches!(cmd, OllyCmd::Ask { .. }),
            _ => false,
        }
    }
}

#[derive(Subcommand)]
enum ProfilesCmd {
    /// List all configured profiles.
    List,
    /// Add or reconfigure a profile interactively.
    Add {
        /// Profile name to configure (prompted if not provided).
        #[arg(add = ArgValueCompleter::new(complete_profile_names))]
        name: Option<String>,
        /// Set this profile as the default without prompting.
        #[arg(long)]
        set_default: bool,
    },
    /// Delete a profile and its stored credentials.
    Delete {
        /// Profile name to delete.
        #[arg(add = ArgValueCompleter::new(complete_profile_names))]
        name: String,
        /// Skip confirmation prompt.
        #[arg(long, short = 'f')]
        force: bool,
    },
    /// Set the default profile.
    SetDefault {
        /// Profile name to set as default.
        #[arg(add = ArgValueCompleter::new(complete_profile_names))]
        name: String,
    },
}

#[derive(Subcommand)]
enum DataprimeCmd {
    /// List all available DataPrime commands and functions.
    List {
        /// Filter by type: commands, functions, or all.
        #[arg(long, default_value = "all")]
        filter: DataprimeFilter,

        /// Filter by name pattern (substring match).
        #[arg(long)]
        name: Option<String>,
    },

    /// Show detailed documentation for a command or function.
    Show {
        /// Name of the command or function.
        name: String,
    },

    /// Execute a raw DataPrime query. Either include a `source` command in the
    /// query itself or use `--source` to set the default source.
    #[command(after_help = "\
Examples:
  cx dataprime query 'source logs | filter $m.severity == \"ERROR\"'
  cx dataprime query --source logs 'filter $m.severity == ERROR'
  cx dataprime query --source spans 'filter $m.duration > 1000000' --start now-6h
  cx dataprime query 'source logs | groupby $l.subsystemname aggregate count()' --limit 50")]
    Query {
        /// DataPrime query string. Include a `source` command in the query
        /// or use --source to set the default source.
        query: String,

        /// Default source for the query (e.g. "logs", "spans"). Equivalent to
        /// starting the query with `source <value>`. Ignored if the query
        /// already contains an explicit `source` command.
        #[arg(long, short = 's')]
        source: Option<String>,

        /// Start time in ISO 8601 or relative format. e.g. "2024-01-01T00:00:00Z" or "now-1h"
        #[arg(long, default_value = "now-1h")]
        start: String,

        /// End time in ISO 8601 or relative format.
        #[arg(long, default_value = "now")]
        end: String,

        /// Maximum number of results.
        #[arg(long, default_value_t = 100)]
        limit: u32,

        /// Storage tier to search. Overrides the profile's default_tier setting.
        /// If neither is set, defaults to archive.
        #[arg(long)]
        tier: Option<Tier>,
    },
}

#[derive(Subcommand)]
enum OllyCmd {
    /// Send a message to the AI assistant.
    #[command(after_help = "\
Examples:
  cx olly ask \"What alerts fired today?\"
  cx olly ask \"Show me error logs\" --chat-id <uuid>
  cx olly ask \"Analyze this\" --model claude-sonnet-4-5")]
    Ask {
        /// The message to send to the assistant.
        message: String,

        /// Continue an existing chat (omit to create a new chat).
        #[arg(long)]
        chat_id: Option<String>,

        /// Model choice (e.g., gpt-5.2, claude-sonnet-4-5, gpt-5.4, claude-haiku-4-5).
        #[arg(long, default_value = "gpt-5.2")]
        model: String,

        /// Timeout in seconds for response.
        #[arg(long, default_value_t = 900)]
        timeout: u32,
    },

    /// Manage artifacts from assistant responses.
    Artifacts {
        #[command(subcommand)]
        cmd: OllyArtifactsCmd,
    },
}

#[derive(Subcommand)]
enum OllyArtifactsCmd {
    /// List all artifacts.
    #[command(after_help = "\
Examples:
  cx olly artifacts list
  cx olly artifacts list -o json")]
    List,

    /// Get an artifact's download URL.
    #[command(after_help = "\
Examples:
  cx olly artifacts get <artifact-id>
  cx olly artifacts get <artifact-id> -o json")]
    Get {
        /// Artifact ID (UUID from the assistant's response).
        artifact_id: String,
    },
}

#[derive(Subcommand)]
enum MetricsCmd {
    /// Execute a PromQL instant query.
    #[command(after_help = "\
Examples:
  cx metrics query 'up'
  cx metrics query 'rate(http_requests_total[5m])' --time 2026-03-21T00:00:00Z")]
    Query {
        /// PromQL expression. e.g. 'up' or 'rate(http_requests_total[5m])'
        expr: String,

        /// Evaluation timestamp (Unix timestamp or RFC3339). Defaults to now.
        #[arg(long)]
        time: Option<String>,
    },

    /// Execute a PromQL range query.
    #[command(after_help = "\
Examples:
  cx metrics query-range 'rate(http_requests_total[5m])'
  cx metrics query-range 'sum by (service) (rate(http_requests_total[5m]))' --start now-6h --step 30s")]
    QueryRange {
        /// PromQL expression. e.g. 'rate(http_requests_total[5m])'
        expr: String,

        /// Start time (Unix timestamp or RFC3339).
        #[arg(long, default_value = "now-1h")]
        start: String,

        /// End time (Unix timestamp or RFC3339).
        #[arg(long, default_value = "now")]
        end: String,

        /// Query resolution step. e.g. "1m", "30s"
        #[arg(long, default_value = "1m")]
        step: String,
    },

    /// Search available metric names.
    #[command(after_help = "\
Examples:
  cx metrics search --name 'http_*'
  cx metrics search --description \"request error rate\"")]
    Search {
        /// Filter by metric name using a substring or wildcard pattern (* matches any sequence).
        #[arg(long, conflicts_with = "description")]
        name: Option<String>,

        /// Filter by description (semantic search using embeddings).
        #[arg(long, conflicts_with = "name")]
        description: Option<String>,
    },

    /// Retrieve all label names for a specific metric.
    GetLabels {
        /// Metric name to retrieve labels for. e.g. 'http_requests_total'
        metric: String,
    },
}

#[derive(Subcommand)]
enum DashboardsCmd {
    /// List all dashboards in the catalog.
    #[command(after_help = "\
Examples:
  cx dashboards catalog
  cx dashboards catalog -o json")]
    Catalog,
    /// Get a single dashboard by ID.
    Get {
        /// Dashboard ID.
        dashboard_id: String,
    },
    /// Create a new dashboard from a JSON definition file [requires --yes].
    #[command(after_help = "\
Examples:
  cx dashboards create --from-file dashboard.json
  cx dashboards create --from-file dashboard.json --folder <folder-id>
  cat dashboard.json | cx dashboards create")]
    Create {
        /// Path to a JSON file with the dashboard definition. Use '-' for stdin.
        /// Accepts either a bare dashboard document or a `{\"dashboard\": {...}}` wrapper;
        /// the `requestId` envelope field is generated automatically.
        #[arg(long, default_value = "-")]
        from_file: String,

        /// Optional folder ID to place the dashboard in. Look up with
        /// `cx dashboards folders list`.
        #[arg(long)]
        folder: Option<String>,
    },
    /// Replace an existing dashboard with an updated JSON definition [requires --yes].
    #[command(after_help = "\
Examples:
  cx dashboards get <id> -o json > dash.json
  # edit dash.json...
  cx dashboards replace --from-file dash.json
  cat dash.json | cx dashboards replace")]
    Replace {
        /// Path to a JSON file with the updated dashboard definition. Use '-' for stdin.
        /// The JSON must include the dashboard `id` field. Accepts either a bare dashboard
        /// document or a `{"dashboard": {...}}` wrapper; the `requestId` envelope field
        /// is generated automatically.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a dashboard [requires --yes].
    Delete {
        /// Dashboard ID.
        dashboard_id: String,
    },
    /// Search dashboards semantically by description.
    #[command(after_help = "\
Examples:
  cx dashboards search \"kubernetes pod memory\"
  cx dashboards search \"latency over time\" --limit 5")]
    Search {
        /// Natural-language description to search for.
        description: String,

        /// Maximum number of results to return.
        #[arg(long, default_value_t = 10)]
        limit: u32,
    },

    /// Search dashboard queries by field reference or description.
    #[command(after_help = "\
Examples:
  cx dashboards query-search --field \"$d.http.status\"
  cx dashboards query-search --description \"http error rate\"
  cx dashboards query-search --description \"cpu usage\" --limit 5")]
    QuerySearch {
        /// Find queries that reference a specific field path.
        #[arg(long, conflicts_with = "description")]
        field: Option<String>,

        /// Find queries matching a natural-language description.
        #[arg(long, conflicts_with = "field")]
        description: Option<String>,

        /// Maximum number of results to return.
        #[arg(long, default_value_t = 10)]
        limit: u32,
    },

    /// Manage dashboard folders.
    Folders {
        #[command(subcommand)]
        cmd: FoldersCmd,
    },
}

#[derive(Subcommand)]
enum FoldersCmd {
    /// List all dashboard folders.
    #[command(after_help = "\
Examples:
  cx dashboards folders list
  cx dashboards folders list -o json")]
    List,
    /// Create a new dashboard folder [requires --yes].
    #[command(after_help = "\
Examples:
  cx dashboards folders create --name \"My Service\"
  cx dashboards folders create --name \"Sub-folder\" --parent-id <folder-id>")]
    Create {
        /// Folder name (required, must be unique within its parent).
        #[arg(long)]
        name: String,

        /// Optional parent folder ID. Omit to create a top-level folder.
        #[arg(long)]
        parent_id: Option<String>,
    },
    /// Delete a dashboard folder [requires --yes].
    Delete {
        /// Folder ID.
        id: String,
    },
}

#[derive(Subcommand)]
enum AlertsCmd {
    /// List all alerts.
    #[command(after_help = "\
Examples:
  cx alerts list
  cx alerts list --name \"payment\"")]
    List {
        /// Filter by name (case-insensitive substring match).
        #[arg(long)]
        name: Option<String>,
    },
    /// Get a single alert definition by ID.
    Get {
        /// Alert definition ID or alert version ID (UUID). The alert definition ID is tried
        /// first; if not found, the ID is retried as an alert version ID.
        alert_id: String,
    },
    /// Create an alert from a JSON definition file [requires --yes].
    #[command(after_help = "\
Examples:
  cx alerts create --from-file alert.json
  cat alert.json | cx alerts create")]
    Create {
        /// Path to JSON file with the alert definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete an alert [requires --yes].
    Delete {
        /// Alert definition ID (UUID).
        alert_id: String,
    },
    /// Enable an alert [requires --yes].
    Enable {
        /// Alert definition ID (UUID).
        alert_id: String,
    },
    /// Disable an alert [requires --yes].
    Disable {
        /// Alert definition ID (UUID).
        alert_id: String,
    },
    /// List alert events (trigger instances).
    #[command(after_help = "\
Examples:
  cx alerts events
  cx alerts events --alert-id <id>
  cx alerts events --start now-24h")]
    Events {
        /// Filter by alert definition ID.
        #[arg(long)]
        alert_id: Option<String>,

        /// Start time filter (ISO 8601 or relative).
        #[arg(long)]
        start: Option<String>,

        /// End time filter (ISO 8601 or relative).
        #[arg(long)]
        end: Option<String>,
    },
    /// Get alert event statistics.
    EventStats,
    /// Manage alert suppression rules.
    #[command(after_help = "\
Examples:
  cx alerts suppression-rules list
  cx alerts suppression-rules get <rule-id>
  cx alerts suppression-rules create --from-file rule.json
  cx alerts suppression-rules delete <rule-id>")]
    SuppressionRules {
        #[command(subcommand)]
        cmd: SuppressionRulesCmd,
    },
}

#[derive(Subcommand)]
enum IncidentsCmd {
    /// List incidents with optional filters.
    #[command(after_help = "\
Examples:
  cx incidents list
  cx incidents list --severity CRITICAL
  cx incidents list --status TRIGGERED")]
    List {
        /// Filter by status (e.g. TRIGGERED, ACKNOWLEDGED, RESOLVED).
        #[arg(long)]
        status: Option<String>,

        /// Filter by severity (e.g. CRITICAL, WARNING, INFO).
        #[arg(long)]
        severity: Option<String>,

        /// Filter by assignee user ID.
        #[arg(long)]
        assignee: Option<String>,
    },
    /// Get a single incident by ID.
    Get {
        /// Incident ID.
        id: String,
    },
    /// Acknowledge one or more incidents [requires --yes].
    Acknowledge {
        /// Incident IDs to acknowledge.
        #[arg(required = true)]
        ids: Vec<String>,
    },
    /// Resolve one or more incidents [requires --yes].
    Resolve {
        /// Incident IDs to resolve.
        #[arg(required = true)]
        ids: Vec<String>,
    },
    /// Close one or more incidents [requires --yes].
    Close {
        /// Incident IDs to close.
        #[arg(required = true)]
        ids: Vec<String>,
    },
    /// Assign one or more incidents to a user [requires --yes].
    Assign {
        /// Incident IDs to assign.
        #[arg(required = true)]
        ids: Vec<String>,

        /// User ID to assign to.
        #[arg(long)]
        user_id: String,
    },
    /// Unassign one or more incidents [requires --yes].
    Unassign {
        /// Incident IDs to unassign.
        #[arg(required = true)]
        ids: Vec<String>,
    },
    /// List incident events.
    #[command(after_help = "\
Examples:
  cx incidents events
  cx incidents events --incident-id <id>")]
    Events {
        /// Filter events by incident ID.
        #[arg(long)]
        incident_id: Option<String>,
    },
    /// Get incident aggregations.
    Aggregations,
}

#[derive(Subcommand)]
enum SuppressionRulesCmd {
    /// List all suppression rules.
    List,
    /// Get a single suppression rule by ID.
    Get {
        /// Suppression rule ID.
        id: String,
    },
    /// Create a suppression rule from a JSON definition file [requires --yes].
    #[command(after_help = "\
Examples:
  cx alerts suppression-rules create --from-file rule.json
  cat rule.json | cx alerts suppression-rules create")]
    Create {
        /// Path to JSON file with the rule definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a suppression rule from a JSON definition file [requires --yes].
    Update {
        /// Path to JSON file with the updated rule definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a suppression rule [requires --yes].
    Delete {
        /// Suppression rule ID.
        id: String,
    },
}

#[derive(Subcommand)]
enum NotificationsCmd {
    /// Manage notification connectors.
    #[command(after_help = "\
Examples:
  cx notifications connectors list
  cx notifications connectors get <connector-id>
  cx notifications connectors types")]
    Connectors {
        #[command(subcommand)]
        cmd: ConnectorsCmd,
    },
    /// Manage notification routers.
    #[command(after_help = "\
Examples:
  cx notifications routers list
  cx notifications routers get <router-id>")]
    Routers {
        #[command(subcommand)]
        cmd: RoutersCmd,
    },
    /// Manage notification presets.
    #[command(after_help = "\
Examples:
  cx notifications presets list
  cx notifications presets get <preset-id>")]
    Presets {
        #[command(subcommand)]
        cmd: PresetsCmd,
    },
    /// Test notification configurations.
    Test {
        #[command(subcommand)]
        cmd: NotificationTestCmd,
    },
}

#[derive(Subcommand)]
enum ConnectorsCmd {
    /// List all notification connectors.
    List,
    /// Get a single connector by ID.
    Get { id: String },
    /// Create a connector from a JSON definition file [requires --yes].
    Create {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Replace a connector definition from a JSON file [requires --yes].
    Update {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a connector [requires --yes].
    Delete { id: String },
    /// List connector type summaries.
    Types,
    /// List entity types.
    EntityTypes,
    /// List entity subtypes for a given type.
    EntitySubtypes {
        /// Entity type name.
        #[arg(long, rename_all = "kebab-case")]
        r#type: String,
    },
}

#[derive(Subcommand)]
enum RoutersCmd {
    /// List all notification routers.
    List,
    /// Get a single router by ID.
    Get { id: String },
    /// Create a router from a JSON definition file [requires --yes].
    Create {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Replace a router definition from a JSON file [requires --yes].
    Update {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a router [requires --yes].
    Delete { id: String },
    /// Test entity label matcher.
    ValidateMatcher {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
}

#[derive(Subcommand)]
enum PresetsCmd {
    /// List all notification presets.
    List,
    /// Get a single preset by ID.
    Get { id: String },
    /// Create a custom preset from a JSON definition file [requires --yes].
    Create {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Replace a custom preset from a JSON file [requires --yes].
    Update {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a custom preset [requires --yes].
    Delete { id: String },
    /// Set default preset [requires --yes].
    SetDefault { id: String },
}

#[derive(Subcommand)]
enum NotificationTestCmd {
    /// Test connector configuration.
    Connector {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Test destination.
    Destination {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Test preset configuration.
    Preset {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Test routing condition.
    RoutingCondition {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Test template rendering.
    TemplateRender {
        #[arg(long, default_value = "-")]
        from_file: String,
    },
}

#[derive(Subcommand)]
enum DataUsageCmd {
    /// Show data usage overview.
    Summary {
        /// Start time (ISO 8601 or relative, e.g. now-7d). Defaults to 24h ago.
        #[arg(long)]
        start: Option<String>,

        /// End time (ISO 8601 or relative). Defaults to now.
        #[arg(long)]
        end: Option<String>,
    },
    /// Show daily usage breakdown.
    Daily {
        /// Usage type: processed-gbs, units, or evaluation-tokens.
        #[arg(long, default_value = "processed-gbs")]
        r#type: String,

        /// Start time filter (ISO 8601 or relative).
        #[arg(long)]
        start: Option<String>,

        /// End time filter (ISO 8601 or relative).
        #[arg(long)]
        end: Option<String>,
    },
    /// Show logs count.
    LogsCount,
    /// Show spans count.
    SpansCount,
    /// Show export status.
    ExportStatus,
}

#[derive(Subcommand)]
enum TcoPoliciesCmd {
    /// List all TCO policies.
    List,
    /// Get a single TCO policy by ID.
    Get {
        /// TCO policy ID.
        id: String,
    },
    /// Create a TCO policy from a JSON definition file [requires --yes].
    Create {
        /// Path to JSON file with the policy definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a TCO policy from a JSON definition file [requires --yes].
    Update {
        /// Path to JSON file with the updated policy definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a TCO policy [requires --yes].
    Delete {
        /// TCO policy ID.
        id: String,
    },
    /// Reorder TCO policies by priority [requires --yes].
    Reorder {
        /// Path to JSON file with the reorder definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Test TCO policy matching.
    Test {
        /// Path to JSON file with the test definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Show TCO settings.
    Settings,
    /// Replace TCO settings from a JSON file [requires --yes].
    SettingsUpdate {
        /// Path to JSON file with the settings. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
}

#[derive(Subcommand)]
enum RetentionsCmd {
    /// List retention settings.
    List,
    /// Update retention settings from a JSON file [requires --yes].
    Update {
        /// Path to JSON file with retention settings. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Activate retention [requires --yes].
    Activate,
    /// Check retention enabled status.
    Status,
}

#[derive(Subcommand)]
enum E2mCmd {
    /// List all E2M definitions.
    List,
    /// Get a single E2M definition by ID.
    Get {
        /// E2M definition ID.
        id: String,
    },
    /// Create an E2M definition from a JSON file [requires --yes].
    Create {
        /// Path to JSON file with the E2M definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Replace an E2M definition from a JSON file [requires --yes].
    Update {
        /// Path to JSON file with the updated E2M definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete an E2M definition [requires --yes].
    Delete {
        /// E2M definition ID.
        id: String,
    },
    /// Get E2M labels cardinality.
    LabelsCardinality,
    /// Get E2M limits.
    Limits,
}

#[derive(Subcommand)]
enum RecordingRulesCmd {
    /// List all recording rule groups.
    List,
    /// Get a single recording rule group by ID.
    Get {
        /// Recording rule group ID.
        id: String,
    },
    /// Create a recording rule group from a JSON definition file [requires --yes].
    Create {
        /// Path to JSON file with the rule group definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a recording rule group from a JSON definition file [requires --yes].
    Update {
        /// Path to JSON file with the updated rule group definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,

        /// Recording rule group ID.
        id: String,
    },
    /// Delete a recording rule group [requires --yes].
    Delete {
        /// Recording rule group ID.
        id: String,
    },
}

#[derive(Subcommand)]
enum ParsingRulesCmd {
    /// List all parsing rule groups.
    List,
    /// Get a single parsing rule group by ID.
    Get {
        /// Parsing rule group ID.
        id: String,
    },
    /// Create a parsing rule group from a JSON definition file [requires --yes].
    Create {
        /// Path to JSON file with the parsing rule group definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a parsing rule group from a JSON definition file [requires --yes].
    Update {
        /// Path to JSON file with the updated parsing rule group definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
        /// Parsing rule group ID.
        id: String,
    },
    /// Delete a parsing rule group [requires --yes].
    Delete {
        /// Parsing rule group ID.
        id: String,
    },
    /// Bulk delete parsing rule groups by IDs [requires --yes].
    BulkDelete {
        /// Parsing rule group IDs to delete.
        #[arg(long, num_args = 1..)]
        ids: Vec<String>,
    },
    /// Show parsing rule usage limits.
    UsageLimits,
}

#[derive(Subcommand)]
enum EnrichmentsCmd {
    /// List all enrichment rules.
    List,
    /// Add enrichment rules from a JSON file [requires --yes].
    Add {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Remove enrichment rules from a JSON file [requires --yes].
    Remove {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Overwrite all enrichment rules from a JSON file [requires --yes].
    Overwrite {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Show enrichment limits.
    Limit,
    /// Show enrichment settings.
    Settings,
    /// Manage custom enrichment tables.
    #[command(after_help = "\
Examples:
  cx enrichments custom list
  cx enrichments custom get <id>
  cx enrichments custom create --from-file table.json
  cx enrichments custom delete <id>")]
    Custom {
        #[command(subcommand)]
        cmd: CustomEnrichmentsCmd,
    },
}

#[derive(Subcommand)]
enum CustomEnrichmentsCmd {
    /// List all custom enrichment tables.
    List,
    /// Get a custom enrichment table by ID.
    Get {
        /// Custom enrichment table ID.
        id: String,
    },
    /// Create a custom enrichment table from a JSON file [requires --yes].
    Create {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a custom enrichment table from a JSON file [requires --yes].
    Update {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a custom enrichment table [requires --yes].
    Delete {
        /// Custom enrichment table ID.
        id: String,
    },
    /// Search data in a custom enrichment table.
    Search {
        /// Custom enrichment table ID.
        #[arg(long)]
        id: String,
        /// Search query text.
        #[arg(long)]
        query: String,
    },
}

#[derive(Subcommand)]
enum IntegrationsCmd {
    /// List all integrations.
    List,
    /// Get integration details by ID.
    Get {
        /// Integration ID.
        id: String,
    },
    /// Get integration definition by ID.
    Definition {
        /// Integration ID.
        id: String,
    },
    /// Get deployed integration by ID.
    Deployed {
        /// Integration ID.
        id: String,
    },
    /// Create an integration from a JSON file [requires --yes].
    Create {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update an integration from a JSON file [requires --yes].
    Update {
        /// Integration ID.
        id: String,
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete an integration [requires --yes].
    Delete {
        /// Integration ID.
        id: String,
    },
    /// Test an integration configuration.
    Test {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Get integration template.
    Template,
    /// Manage extensions.
    #[command(after_help = "\
Examples:
  cx integrations extensions list
  cx integrations extensions deployed
  cx integrations extensions get <id>")]
    Extensions {
        #[command(subcommand)]
        cmd: ExtensionsCmd,
    },
    /// Manage contextual data integrations.
    #[command(after_help = "\
Examples:
  cx integrations contextual-data list
  cx integrations contextual-data get <id>")]
    ContextualData {
        #[command(subcommand)]
        cmd: ContextualDataCmd,
    },
}

#[derive(Subcommand)]
enum ExtensionsCmd {
    /// List all available extensions.
    List,
    /// Get extension details by ID.
    Get {
        /// Extension ID.
        id: String,
    },
    /// List deployed extensions.
    Deployed,
    /// Deploy an extension from a JSON file [requires --yes].
    Deploy {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a deployed extension from a JSON file [requires --yes].
    Update {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Undeploy an extension from a JSON file [requires --yes].
    Undeploy {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
}

#[derive(Subcommand)]
enum WebhooksCmd {
    /// List all outgoing webhooks.
    List,
    /// Get webhook details by ID.
    Get {
        /// Webhook ID.
        id: String,
    },
    /// Create a webhook from a JSON file [requires --yes].
    Create {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a webhook from a JSON file [requires --yes].
    Update {
        /// Webhook ID.
        id: String,
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a webhook [requires --yes].
    Delete {
        /// Webhook ID.
        id: String,
    },
    /// Test a webhook by ID.
    Test {
        /// Webhook ID.
        id: String,
    },
    /// List available webhook types.
    Types,
    /// Manage actions (automation hooks).
    #[command(after_help = "\
Examples:
  cx webhooks actions list
  cx webhooks actions get <id>
  cx webhooks actions create --from-file action.json
  cx webhooks actions delete <id>")]
    Actions {
        #[command(subcommand)]
        cmd: ActionsCmd,
    },
}

#[derive(Subcommand)]
enum ContextualDataCmd {
    /// List contextual data integrations.
    List,
    /// Get integration details by ID.
    Get {
        /// Integration ID.
        id: String,
    },
    /// Create an integration from a JSON file [requires --yes].
    Create {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update an integration from a JSON file [requires --yes].
    Update {
        /// Integration ID.
        id: String,
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete an integration [requires --yes].
    Delete {
        /// Integration ID.
        id: String,
    },
    /// Get integration definition by ID.
    Definition {
        /// Integration ID.
        id: String,
    },
    /// Test an integration by ID.
    Test {
        /// Integration ID.
        id: String,
    },
}

#[derive(Subcommand)]
enum ViewsCmd {
    /// List all saved views.
    List,
    /// Get a view by ID.
    Get {
        /// View ID.
        id: String,
    },
    /// Create a view from a JSON file [requires --yes].
    Create {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Replace a view from a JSON file [requires --yes].
    Update {
        /// View ID.
        id: String,
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a view [requires --yes].
    Delete {
        /// View ID.
        id: String,
    },
    /// Manage view folders.
    Folders {
        #[command(subcommand)]
        cmd: ViewFoldersCmd,
    },
}

#[derive(Subcommand)]
enum ViewFoldersCmd {
    /// List all view folders.
    List,
    /// Get a folder by ID.
    Get {
        /// Folder ID.
        id: String,
    },
    /// Create a folder from a JSON file [requires --yes].
    Create {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Replace a folder from a JSON file [requires --yes].
    Update {
        /// Folder ID.
        id: String,
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a folder [requires --yes].
    Delete {
        /// Folder ID.
        id: String,
    },
}

#[derive(Subcommand)]
enum IamCmd {
    /// Manage API keys.
    #[command(after_help = "\
Examples:
  cx iam api-keys list
  cx iam api-keys get <id>
  cx iam api-keys create --from-file key.json
  cx iam api-keys send-data-keys
  cx iam api-keys admin list")]
    ApiKeys {
        #[command(subcommand)]
        cmd: ApiKeysCmd,
    },
    /// Manage custom and system roles.
    #[command(after_help = "\
Examples:
  cx iam roles list
  cx iam roles get <id>
  cx iam roles create --from-file role.json
  cx iam roles system")]
    Roles {
        #[command(subcommand)]
        cmd: RolesCmd,
    },
    /// Manage team scopes.
    #[command(after_help = "\
Examples:
  cx iam scopes list
  cx iam scopes get <id>
  cx iam scopes create --from-file scope.json")]
    Scopes {
        #[command(subcommand)]
        cmd: ScopesCmd,
    },
    /// Search and manage team users.
    #[command(after_help = "\
Examples:
  cx iam users search
  cx iam users get <user-id>
  cx iam users create --from-file users.json
  cx iam users set-status --user-ids <id> --status ACTIVE")]
    Users {
        #[command(subcommand)]
        cmd: UsersCmd,
    },
    /// Manage team groups.
    #[command(
        name = "groups",
        after_help = "\
Examples:
  cx iam groups list
  cx iam groups get <id>
  cx iam groups get-by-name <name>
  cx iam groups users <group-id>"
    )]
    TeamGroups {
        #[command(subcommand)]
        cmd: TeamGroupsCmd,
    },
    /// Manage IP access restrictions.
    #[command(after_help = "\
Examples:
  cx iam ip-access get
  cx iam ip-access create --from-file access.json
  cx iam ip-access update --from-file access.json
  cx iam ip-access delete")]
    IpAccess {
        #[command(subcommand)]
        cmd: IpAccessCmd,
    },
}

#[derive(Subcommand)]
enum ApiKeysCmd {
    /// List all API keys.
    List,
    /// Get a single API key by ID.
    Get {
        /// API key ID.
        id: String,
    },
    /// Create an API key from a JSON definition file [requires --yes].
    Create {
        /// Path to JSON file with the API key definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update an API key from a JSON definition file [requires --yes].
    Update {
        /// Path to JSON file with the updated API key definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
        /// API key ID.
        id: String,
    },
    /// Delete an API key [requires --yes].
    Delete {
        /// API key ID.
        id: String,
    },
    /// List send-data API keys.
    SendDataKeys,
    /// Admin operations on team members' API keys.
    Admin {
        #[command(subcommand)]
        cmd: ApiKeysAdminCmd,
    },
}

#[derive(Subcommand)]
enum ApiKeysAdminCmd {
    /// List all team members' API keys.
    List,
    /// Bulk delete API keys by IDs [requires --yes].
    Delete {
        /// API key IDs to delete.
        #[arg(long, num_args = 1..)]
        ids: Vec<String>,
    },
    /// Set active/inactive status for API keys [requires --yes].
    SetStatus {
        /// API key IDs to update.
        #[arg(long, num_args = 1..)]
        ids: Vec<String>,
        /// Whether to activate or deactivate the keys.
        #[arg(long)]
        active: bool,
    },
}

#[derive(Subcommand)]
enum RolesCmd {
    /// List all custom roles.
    List,
    /// Get a single custom role by ID.
    Get {
        /// Role ID.
        id: String,
    },
    /// Create a custom role from a JSON definition file [requires --yes].
    Create {
        /// Path to JSON file with the role definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a custom role from a JSON definition file [requires --yes].
    Update {
        /// Path to JSON file with the updated role definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
        /// Role ID.
        id: String,
    },
    /// Delete a custom role [requires --yes].
    Delete {
        /// Role ID.
        id: String,
    },
    /// List system roles.
    System,
}

#[derive(Subcommand)]
enum ScopesCmd {
    /// List all scopes.
    List,
    /// Get a single scope by ID.
    Get {
        /// Scope ID.
        id: String,
    },
    /// Create a scope from a JSON definition file [requires --yes].
    Create {
        /// Path to JSON file with the scope definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a scope from a JSON definition file [requires --yes].
    Update {
        /// Path to JSON file with the updated scope definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete a scope [requires --yes].
    Delete {
        /// Scope ID.
        id: String,
    },
}

#[derive(Subcommand)]
enum UsersCmd {
    /// Search users.
    Search {
        /// Search query string.
        #[arg(long)]
        query: Option<String>,
        /// Filter by status.
        #[arg(long)]
        status: Option<String>,
        /// Maximum number of results per page.
        #[arg(long)]
        page_size: Option<String>,
        /// Pagination token.
        #[arg(long)]
        page_token: Option<String>,
    },
    /// Get a single user by ID.
    Get {
        /// User ID.
        user_id: String,
    },
    /// Create user(s) from a JSON definition file [requires --yes].
    Create {
        /// Path to JSON file with the user definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update user(s) from a JSON definition file [requires --yes].
    Update {
        /// Path to JSON file with the updated user definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Set status for one or more users [requires --yes].
    SetStatus {
        /// User IDs to update.
        #[arg(long, num_args = 1..)]
        user_ids: Vec<String>,
        /// Status to set (e.g. ACTIVE, INACTIVE).
        #[arg(long)]
        status: String,
    },
}

#[derive(Subcommand)]
enum TeamGroupsCmd {
    /// List all team groups.
    List {},
    /// Get a single team group by ID.
    Get {
        /// Team group ID.
        id: String,
    },
    /// Get a team group by name.
    GetByName {
        /// Team group name.
        name: String,
    },
    /// List users in a team group.
    Users {
        /// Team group ID.
        group_id: String,
    },
    /// Create a team group from a JSON definition file [requires --yes].
    Create {
        /// Path to JSON file with the group definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update a team group from a JSON definition file [requires --yes].
    Update {
        /// Path to JSON file with the updated group definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
        /// Team group ID.
        id: String,
    },
    /// Delete a team group [requires --yes].
    Delete {
        /// Team group ID.
        id: String,
    },
}

#[derive(Subcommand)]
enum IpAccessCmd {
    /// Get IP access settings.
    Get,
    /// Create IP access settings from a JSON file [requires --yes].
    Create {
        /// Path to JSON file with IP access settings. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update IP access settings from a JSON file [requires --yes].
    Update {
        /// Path to JSON file with updated IP access settings. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete IP access settings [requires --yes].
    Delete,
}

#[derive(Subcommand)]
enum ActionsCmd {
    /// List all actions.
    List,
    /// Get action details by ID.
    Get {
        /// Action ID.
        id: String,
    },
    /// Create an action from a JSON file [requires --yes].
    Create {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Replace an action from a JSON file [requires --yes].
    Update {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete an action [requires --yes].
    Delete {
        /// Action ID.
        id: String,
    },
    /// Batch execute actions from a JSON file [requires --yes].
    Batch {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Reorder actions from a JSON file [requires --yes].
    Reorder {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
}

#[derive(Subcommand)]
enum DataArchiveCmd {
    /// Manage metrics archive.
    Metrics {
        #[command(subcommand)]
        cmd: DataArchiveMetricsCmd,
    },
    /// Manage logs archive.
    Logs {
        #[command(subcommand)]
        cmd: DataArchiveLogsCmd,
    },
}

#[derive(Subcommand)]
enum DataArchiveMetricsCmd {
    /// Get metrics archive configuration.
    Get,
    /// Create metrics archive from a JSON file [requires --yes].
    Create {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Update metrics archive from a JSON file [requires --yes].
    Update {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Enable metrics archiving [requires --yes].
    Enable,
    /// Disable metrics archiving [requires --yes].
    Disable,
    /// Validate metrics archive configuration from a JSON file.
    Validate {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
}

#[derive(Subcommand)]
enum DataArchiveLogsCmd {
    /// Get logs archive target.
    Get,
    /// Set logs archive target from a JSON file [requires --yes].
    Set {
        /// Path to JSON file. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
}

#[derive(Subcommand)]
enum SlosCmd {
    /// List all SLOs.
    List,
    /// Get a single SLO by ID.
    Get {
        /// SLO ID (UUID).
        id: String,
    },
    /// Create an SLO from a JSON definition file [requires --yes].
    #[command(after_help = "\
Examples:
  cx slos create --from-file slo.json
  cat slo.json | cx slos create")]
    Create {
        /// Path to JSON file with the SLO definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Replace an SLO definition from a JSON file [requires --yes].
    #[command(after_help = "\
Examples:
  cx slos update --from-file slo.json")]
    Update {
        /// Path to JSON file with the updated SLO definition. Use '-' for stdin.
        #[arg(long, default_value = "-")]
        from_file: String,
    },
    /// Delete an SLO [requires --yes].
    Delete {
        /// SLO ID (UUID).
        id: String,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    // Handle shell completions before any stdout output.
    // When the COMPLETE env var is set (e.g. `COMPLETE=zsh cx`), this generates
    // completion scripts and exits. Otherwise it is a no-op.
    CompleteEnv::with_factory(Cli::command).complete();

    rustls::crypto::ring::default_provider()
        .install_default()
        .expect("Failed to install rustls crypto provider");

    // Check if this is a profiles command - use separate parser without global API flags.
    // Only works when `profiles` is the first arg (no global flags before it).
    if std::env::args().nth(1).as_deref() == Some("profiles") {
        let profiles_cli = ProfilesCli::parse();
        let ProfilesTopLevel::Profiles { cmd } = profiles_cli.command;
        return match cmd {
            ProfilesCmd::List => commands::profiles::run_list(),
            ProfilesCmd::Add { name, set_default } => {
                commands::profiles::run_add(name, set_default).await
            }
            ProfilesCmd::Delete { name, force } => commands::profiles::run_delete(name, force),
            ProfilesCmd::SetDefault { name } => commands::profiles::run_set_default(name),
        };
    }
    // When global flags precede `profiles` (e.g. `cx --read-only profiles list`),
    // the early check above misses it. The main Cli parser handles it below.

    let mut cmd = Cli::command();
    if banner::should_show() {
        cmd = cmd
            .before_help(banner::render())
            .help_template("{before-help}\nUsage: {usage}{after-help}\n\nOptions:\n{options}");
    }
    let matches = cmd.get_matches();
    let cli = Cli::from_arg_matches(&matches)?;

    // Load global config early for read-only / risky / olly gating.
    let global_cfg_early = config::load_config().unwrap_or_default();

    let read_only =
        cli.read_only || safety::env_is_truthy("CX_READ_ONLY") || global_cfg_early.read_only;
    if read_only {
        let top = safety::get_top_level_subcommand_name(&matches);
        let is_local = matches!(
            top.as_deref(),
            Some("profiles") | Some("cleanup") | Some("completions")
        );
        if !is_local {
            if let Some(leaf) = safety::get_leaf_subcommand_name(&matches) {
                safety::enforce_read_only(&leaf)?;
            }
        }
    }

    // Risky command gating (iam, archive write operations).
    if cli.command.is_risky() && !global_cfg_early.allow_risky_commands {
        if let Some(leaf) = safety::get_leaf_subcommand_name(&matches) {
            if safety::is_write_verb(&leaf) {
                bail!(
                    "Risky write operation blocked by global configuration.\n\
                     Set allow_risky_commands = true in ~/.cx/config.toml to enable."
                );
            }
        }
    }

    // Olly gating (olly ask).
    if cli.command.is_olly() && !global_cfg_early.olly_enabled {
        bail!(
            "The Olly AI assistant is currently disabled in your global configuration.\n\
             To enable it, set olly_enabled = true in ~/.cx/config.toml."
        );
    }

    // Profiles command is usually handled by the early ProfilesCli parser above,
    // but when global flags precede `profiles` (e.g. `cx --read-only profiles list`),
    // it falls through to here.
    if let Commands::Profiles { cmd } = cli.command {
        return match cmd {
            ProfilesCmd::List => commands::profiles::run_list(),
            ProfilesCmd::Add { name, set_default } => {
                commands::profiles::run_add(name, set_default).await
            }
            ProfilesCmd::Delete { name, force } => commands::profiles::run_delete(name, force),
            ProfilesCmd::SetDefault { name } => commands::profiles::run_set_default(name),
        };
    }

    // Cleanup command doesn't need API credentials.
    if let Commands::Cleanup = cli.command {
        return commands::cleanup::run();
    }

    // Schema command doesn't need API credentials - outputs command tree as JSON.
    if let Commands::Schema = cli.command {
        return commands::schema::run(Cli::command());
    }

    // Completions commands don't need API credentials.
    if let Commands::Completions { cmd } = cli.command {
        return match cmd {
            CompletionsCmd::Generate { shell } => {
                commands::completions::run_generate(shell, &mut Cli::command())
            }
            CompletionsCmd::Install { shell, path } => {
                commands::completions::run_install(shell, path, &mut Cli::command())
            }
            CompletionsCmd::Refresh => commands::completions::run_refresh(Cli::command),
        };
    }

    // Dataprime list/show don't need API credentials - handle them early.
    if let Commands::Dataprime { ref cmd } = cli.command {
        if matches!(cmd, DataprimeCmd::List { .. } | DataprimeCmd::Show { .. }) {
            let global_config = config::load_config().unwrap_or_default();
            let output = cli.output.unwrap_or(global_config.default_output_format);
            return match cmd {
                DataprimeCmd::List { filter, name } => {
                    commands::dataprime::run_list(*filter, name.as_deref(), output)
                }
                DataprimeCmd::Show { name } => commands::dataprime::run_help(name, output),
                // Query needs credentials - handled in the main match below.
                DataprimeCmd::Query { .. } => unreachable!(),
            };
        }
        // DataprimeCmd::Query needs credentials - fall through.
    }

    // When the user names a profile explicitly via --profile but did NOT pass
    // --api-key / --region on the command line, suppress the corresponding
    // env-var value (CX_API_KEY / CX_REGION) so the profile's own stored
    // credentials and region are used instead.
    let profile_from_cli = matches.value_source("profile") == Some(ValueSource::CommandLine);
    let api_key_from_cli = matches.value_source("api_key") == Some(ValueSource::CommandLine);
    let region_from_cli = matches.value_source("region") == Some(ValueSource::CommandLine);
    let effective_api_key: Option<&str> = if profile_from_cli && !api_key_from_cli {
        None
    } else {
        cli.api_key.as_deref()
    };
    let effective_region: Option<&str> = if profile_from_cli && !region_from_cli {
        None
    } else {
        cli.region.as_deref()
    };

    // Reject --api-key / --region when more than one --profile is supplied,
    // because it would be ambiguous which profile the override targets.
    if cli.profile.len() > 1 && (effective_api_key.is_some() || effective_region.is_some()) {
        bail!(
            "Cannot combine multiple --profile values with --api-key or --region overrides.\n\
             Store per-profile credentials with `cx profiles add <name>`."
        );
    }

    // Load global config for defaults (non-fatal - fall back to defaults).
    let global_config = config::load_config().unwrap_or_default();
    let output = cli
        .output
        .or_else(|| config::first_profile_output_format(&cli.profile))
        .unwrap_or(global_config.default_output_format);
    let max_direct = global_config.max_dataprime_direct_output_size;
    let temp_dir = global_config.temp_dir.clone();

    // Resolve one or more profiles into execution targets.
    let configs = config::resolve_all(&cli.profile, effective_api_key, effective_region)
        .await
        .map_err(|e| {
            eprintln!("Configuration error: {e}");
            eprintln!("Run `cx profiles add` to set up credentials.");
            e
        })?;

    let targets = build_targets(configs)?;
    let yes = cli.yes;
    let agent_mode = safety::is_agent_mode();

    match cli.command {
        Commands::Profiles { .. } => unreachable!("handled by ProfilesCli above"),
        Commands::Cleanup => unreachable!("handled above"),
        Commands::Schema => unreachable!("handled above"),
        Commands::Completions { .. } => unreachable!("handled above"),

        Commands::Dataprime { cmd } => match cmd {
            DataprimeCmd::List { .. } | DataprimeCmd::Show { .. } => {
                unreachable!("handled above")
            }
            DataprimeCmd::Query {
                query,
                source,
                start,
                end,
                limit,
                tier,
            } => {
                commands::dataprime::run_query(
                    &targets,
                    &query,
                    source.as_deref().unwrap_or(""),
                    &start,
                    &end,
                    limit,
                    tier,
                    output,
                    max_direct,
                    &temp_dir,
                    None,
                )
                .await?;
            }
        },

        Commands::Logs {
            query,
            start,
            end,
            limit,
            tier,
        } => {
            commands::logs::run(
                &targets, &query, &start, &end, limit, tier, output, max_direct, &temp_dir,
            )
            .await?;
        }

        Commands::Metrics { cmd } => match cmd {
            MetricsCmd::Query { expr, time } => {
                commands::metrics::run_query(&targets, &expr, time.as_deref(), output).await?;
            }
            MetricsCmd::QueryRange {
                expr,
                start,
                end,
                step,
            } => {
                commands::metrics::run_query_range(&targets, &expr, &start, &end, &step, output)
                    .await?;
            }
            MetricsCmd::Search { name, description } => {
                commands::metrics::run_search(
                    &targets,
                    name.as_deref(),
                    description.as_deref(),
                    output,
                )
                .await?;
            }
            MetricsCmd::GetLabels { metric } => {
                commands::metrics::run_get_labels(&targets, &metric, output).await?;
            }
        },

        Commands::Spans {
            query,
            start,
            end,
            limit,
            tier,
        } => {
            commands::spans::run(
                &targets, &query, &start, &end, limit, tier, output, max_direct, &temp_dir,
            )
            .await?;
        }

        Commands::Dashboards { cmd } => match cmd {
            DashboardsCmd::Catalog => {
                commands::dashboards::run_catalog(&targets, output).await?;
            }
            DashboardsCmd::Get { dashboard_id } => {
                commands::dashboards::run_get(&targets, &dashboard_id, output).await?;
            }
            DashboardsCmd::Create { from_file, folder } => {
                confirm_destructive("Create a new dashboard?", yes, agent_mode)?;
                commands::dashboards::run_create(&targets, &from_file, folder.as_deref(), output)
                    .await?;
            }
            DashboardsCmd::Replace { from_file } => {
                commands::dashboards::run_replace(&targets, &from_file, output, yes, agent_mode)
                    .await?;
            }
            DashboardsCmd::Delete { dashboard_id } => {
                confirm_destructive(
                    &format!("Delete dashboard '{dashboard_id}'?"),
                    yes,
                    agent_mode,
                )?;
                commands::dashboards::run_delete(&targets, &dashboard_id).await?;
            }
            DashboardsCmd::Search { description, limit } => {
                commands::dashboards::run_semantic_search(&targets, &description, limit, output)
                    .await?;
            }
            DashboardsCmd::QuerySearch {
                field,
                description,
                limit,
            } => match (field.as_deref(), description.as_deref()) {
                (Some(f), _) => {
                    commands::dashboards::run_queries_by_field(&targets, f, limit, output).await?;
                }
                (_, Some(d)) => {
                    commands::dashboards::run_search(&targets, d, limit, output).await?;
                }
                (None, None) => {
                    bail!("specify --field or --description");
                }
            },
            DashboardsCmd::Folders { cmd } => match cmd {
                FoldersCmd::List => {
                    commands::dashboards::run_folders_list(&targets, output).await?;
                }
                FoldersCmd::Create { name, parent_id } => {
                    confirm_destructive("Create a new dashboard folder?", yes, agent_mode)?;
                    commands::dashboards::run_folders_create(
                        &targets,
                        &name,
                        parent_id.as_deref(),
                        output,
                    )
                    .await?;
                }
                FoldersCmd::Delete { id } => {
                    confirm_destructive(
                        &format!("Delete dashboard folder '{id}'?"),
                        yes,
                        agent_mode,
                    )?;
                    commands::dashboards::run_folders_delete(&targets, &id).await?;
                }
            },
        },

        Commands::Alerts { cmd } => match cmd {
            AlertsCmd::List { name } => {
                commands::alerts::run_list(&targets, name.as_deref(), output).await?;
            }
            AlertsCmd::Get { alert_id } => {
                commands::alerts::run_get(&targets, &alert_id, output).await?;
            }
            AlertsCmd::Create { from_file } => {
                confirm_destructive("Create a new alert?", yes, agent_mode)?;
                commands::alerts::run_create(&targets, &from_file, output).await?;
            }
            AlertsCmd::Delete { alert_id } => {
                confirm_destructive(&format!("Delete alert '{alert_id}'?"), yes, agent_mode)?;
                commands::alerts::run_delete(&targets, &alert_id).await?;
            }
            AlertsCmd::Enable { alert_id } => {
                confirm_destructive(&format!("Enable alert '{alert_id}'?"), yes, agent_mode)?;
                commands::alerts::run_enable(&targets, &alert_id).await?;
            }
            AlertsCmd::Disable { alert_id } => {
                confirm_destructive(&format!("Disable alert '{alert_id}'?"), yes, agent_mode)?;
                commands::alerts::run_disable(&targets, &alert_id).await?;
            }
            AlertsCmd::Events {
                alert_id,
                start,
                end,
            } => {
                commands::alerts::run_events(
                    &targets,
                    alert_id.as_deref(),
                    start.as_deref(),
                    end.as_deref(),
                    output,
                )
                .await?;
            }
            AlertsCmd::EventStats => {
                commands::alerts::run_event_stats(&targets, output).await?;
            }
            AlertsCmd::SuppressionRules { cmd } => match cmd {
                SuppressionRulesCmd::List => {
                    commands::suppression_rules::run_list(&targets, output).await?;
                }
                SuppressionRulesCmd::Get { id } => {
                    commands::suppression_rules::run_get(&targets, &id, output).await?;
                }
                SuppressionRulesCmd::Create { from_file } => {
                    confirm_destructive("Create a new suppression rule?", yes, agent_mode)?;
                    commands::suppression_rules::run_create(&targets, &from_file, output).await?;
                }
                SuppressionRulesCmd::Update { from_file } => {
                    confirm_destructive("Update suppression rule?", yes, agent_mode)?;
                    commands::suppression_rules::run_update(&targets, &from_file, output).await?;
                }
                SuppressionRulesCmd::Delete { id } => {
                    confirm_destructive(
                        &format!("Delete suppression rule '{id}'?"),
                        yes,
                        agent_mode,
                    )?;
                    commands::suppression_rules::run_delete(&targets, &id).await?;
                }
            },
        },

        Commands::Incidents { cmd } => match cmd {
            IncidentsCmd::List {
                status,
                severity,
                assignee,
            } => {
                commands::incidents::run_list(
                    &targets,
                    status.as_deref(),
                    severity.as_deref(),
                    assignee.as_deref(),
                    output,
                )
                .await?;
            }
            IncidentsCmd::Get { id } => {
                commands::incidents::run_get(&targets, &id, output).await?;
            }
            IncidentsCmd::Acknowledge { ids } => {
                confirm_destructive("Acknowledge incident(s)?", yes, agent_mode)?;
                commands::incidents::run_acknowledge(&targets, &ids).await?;
            }
            IncidentsCmd::Resolve { ids } => {
                confirm_destructive("Resolve incident(s)?", yes, agent_mode)?;
                commands::incidents::run_resolve(&targets, &ids).await?;
            }
            IncidentsCmd::Close { ids } => {
                confirm_destructive("Close incident(s)?", yes, agent_mode)?;
                commands::incidents::run_close(&targets, &ids).await?;
            }
            IncidentsCmd::Assign { ids, user_id } => {
                confirm_destructive(
                    &format!("Assign incident(s) to '{user_id}'?"),
                    yes,
                    agent_mode,
                )?;
                commands::incidents::run_assign(&targets, &ids, &user_id).await?;
            }
            IncidentsCmd::Unassign { ids } => {
                confirm_destructive("Unassign incident(s)?", yes, agent_mode)?;
                commands::incidents::run_unassign(&targets, &ids).await?;
            }
            IncidentsCmd::Events { incident_id } => {
                commands::incidents::run_events(&targets, incident_id.as_deref(), output).await?;
            }
            IncidentsCmd::Aggregations => {
                commands::incidents::run_aggregations(&targets, output).await?;
            }
        },

        Commands::Notifications { cmd } => match cmd {
            NotificationsCmd::Connectors { cmd } => match cmd {
                ConnectorsCmd::List => {
                    commands::connectors::run_list(&targets, output).await?;
                }
                ConnectorsCmd::Get { id } => {
                    commands::connectors::run_get(&targets, &id, output).await?;
                }
                ConnectorsCmd::Create { from_file } => {
                    confirm_destructive("Create a new connector?", yes, agent_mode)?;
                    commands::connectors::run_create(&targets, &from_file, output).await?;
                }
                ConnectorsCmd::Update { from_file } => {
                    confirm_destructive("Update connector?", yes, agent_mode)?;
                    commands::connectors::run_update(&targets, &from_file, output).await?;
                }
                ConnectorsCmd::Delete { id } => {
                    confirm_destructive(&format!("Delete connector '{id}'?"), yes, agent_mode)?;
                    commands::connectors::run_delete(&targets, &id).await?;
                }
                ConnectorsCmd::Types => {
                    commands::connectors::run_types(&targets, output).await?;
                }
                ConnectorsCmd::EntityTypes => {
                    commands::connectors::run_entity_types(&targets, output).await?;
                }
                ConnectorsCmd::EntitySubtypes { r#type } => {
                    commands::connectors::run_entity_subtypes(&targets, &r#type, output).await?;
                }
            },
            NotificationsCmd::Routers { cmd } => match cmd {
                RoutersCmd::List => {
                    commands::routers::run_list(&targets, output).await?;
                }
                RoutersCmd::Get { id } => {
                    commands::routers::run_get(&targets, &id, output).await?;
                }
                RoutersCmd::Create { from_file } => {
                    confirm_destructive("Create a new router?", yes, agent_mode)?;
                    commands::routers::run_create(&targets, &from_file, output).await?;
                }
                RoutersCmd::Update { from_file } => {
                    confirm_destructive("Update router?", yes, agent_mode)?;
                    commands::routers::run_update(&targets, &from_file, output).await?;
                }
                RoutersCmd::Delete { id } => {
                    confirm_destructive(&format!("Delete router '{id}'?"), yes, agent_mode)?;
                    commands::routers::run_delete(&targets, &id).await?;
                }
                RoutersCmd::ValidateMatcher { from_file } => {
                    commands::routers::run_validate_matcher(&targets, &from_file, output).await?;
                }
            },
            NotificationsCmd::Presets { cmd } => match cmd {
                PresetsCmd::List => {
                    commands::presets::run_list(&targets, output).await?;
                }
                PresetsCmd::Get { id } => {
                    commands::presets::run_get(&targets, &id, output).await?;
                }
                PresetsCmd::Create { from_file } => {
                    confirm_destructive("Create a new preset?", yes, agent_mode)?;
                    commands::presets::run_create(&targets, &from_file, output).await?;
                }
                PresetsCmd::Update { from_file } => {
                    confirm_destructive("Update preset?", yes, agent_mode)?;
                    commands::presets::run_update(&targets, &from_file, output).await?;
                }
                PresetsCmd::Delete { id } => {
                    confirm_destructive(&format!("Delete preset '{id}'?"), yes, agent_mode)?;
                    commands::presets::run_delete(&targets, &id).await?;
                }
                PresetsCmd::SetDefault { id } => {
                    confirm_destructive(
                        &format!("Set preset '{id}' as default?"),
                        yes,
                        agent_mode,
                    )?;
                    commands::presets::run_set_default(&targets, &id).await?;
                }
            },
            NotificationsCmd::Test { cmd } => match cmd {
                NotificationTestCmd::Connector { from_file } => {
                    commands::notification_testing::run_test_connector(
                        &targets, &from_file, output,
                    )
                    .await?;
                }
                NotificationTestCmd::Destination { from_file } => {
                    commands::notification_testing::run_test_destination(
                        &targets, &from_file, output,
                    )
                    .await?;
                }
                NotificationTestCmd::Preset { from_file } => {
                    commands::notification_testing::run_test_preset(&targets, &from_file, output)
                        .await?;
                }
                NotificationTestCmd::RoutingCondition { from_file } => {
                    commands::notification_testing::run_test_routing_condition(
                        &targets, &from_file, output,
                    )
                    .await?;
                }
                NotificationTestCmd::TemplateRender { from_file } => {
                    commands::notification_testing::run_test_template_render(
                        &targets, &from_file, output,
                    )
                    .await?;
                }
            },
        },

        Commands::DataUsage { cmd } => match cmd {
            DataUsageCmd::Summary { start, end } => {
                commands::data_usage::run_summary(
                    &targets,
                    start.as_deref(),
                    end.as_deref(),
                    output,
                )
                .await?;
            }
            DataUsageCmd::Daily { r#type, start, end } => {
                commands::data_usage::run_daily(
                    &targets,
                    &r#type,
                    start.as_deref(),
                    end.as_deref(),
                    output,
                )
                .await?;
            }
            DataUsageCmd::LogsCount => {
                commands::data_usage::run_logs_count(&targets, output).await?;
            }
            DataUsageCmd::SpansCount => {
                commands::data_usage::run_spans_count(&targets, output).await?;
            }
            DataUsageCmd::ExportStatus => {
                commands::data_usage::run_export_status(&targets, output).await?;
            }
        },

        Commands::TcoPolicies { cmd } => match cmd {
            TcoPoliciesCmd::List => {
                commands::tco_policies::run_list(&targets, output).await?;
            }
            TcoPoliciesCmd::Get { id } => {
                commands::tco_policies::run_get(&targets, &id, output).await?;
            }
            TcoPoliciesCmd::Create { from_file } => {
                confirm_destructive("Create a new TCO policy?", yes, agent_mode)?;
                commands::tco_policies::run_create(&targets, &from_file, output).await?;
            }
            TcoPoliciesCmd::Update { from_file } => {
                confirm_destructive("Update TCO policy?", yes, agent_mode)?;
                commands::tco_policies::run_update(&targets, &from_file, output).await?;
            }
            TcoPoliciesCmd::Delete { id } => {
                confirm_destructive(&format!("Delete TCO policy '{id}'?"), yes, agent_mode)?;
                commands::tco_policies::run_delete(&targets, &id).await?;
            }
            TcoPoliciesCmd::Reorder { from_file } => {
                confirm_destructive("Reorder TCO policies?", yes, agent_mode)?;
                commands::tco_policies::run_reorder(&targets, &from_file, output).await?;
            }
            TcoPoliciesCmd::Test { from_file } => {
                commands::tco_policies::run_test(&targets, &from_file, output).await?;
            }
            TcoPoliciesCmd::Settings => {
                commands::tco_policies::run_settings(&targets, output).await?;
            }
            TcoPoliciesCmd::SettingsUpdate { from_file } => {
                confirm_destructive("Update TCO settings?", yes, agent_mode)?;
                commands::tco_policies::run_settings_update(&targets, &from_file, output).await?;
            }
        },

        Commands::Retentions { cmd } => match cmd {
            RetentionsCmd::List => {
                commands::retentions::run_list(&targets, output).await?;
            }
            RetentionsCmd::Update { from_file } => {
                confirm_destructive("Update retention settings?", yes, agent_mode)?;
                commands::retentions::run_update(&targets, &from_file, output).await?;
            }
            RetentionsCmd::Activate => {
                confirm_destructive("Activate retention settings?", yes, agent_mode)?;
                commands::retentions::run_activate(&targets).await?;
            }
            RetentionsCmd::Status => {
                commands::retentions::run_status(&targets, output).await?;
            }
        },

        Commands::E2m { cmd } => match cmd {
            E2mCmd::List => {
                commands::e2m::run_list(&targets, output).await?;
            }
            E2mCmd::Get { id } => {
                commands::e2m::run_get(&targets, &id, output).await?;
            }
            E2mCmd::Create { from_file } => {
                confirm_destructive("Create a new E2M definition?", yes, agent_mode)?;
                commands::e2m::run_create(&targets, &from_file, output).await?;
            }
            E2mCmd::Update { from_file } => {
                confirm_destructive("Update E2M definition?", yes, agent_mode)?;
                commands::e2m::run_update(&targets, &from_file, output).await?;
            }
            E2mCmd::Delete { id } => {
                confirm_destructive(&format!("Delete E2M definition '{id}'?"), yes, agent_mode)?;
                commands::e2m::run_delete(&targets, &id).await?;
            }
            E2mCmd::LabelsCardinality => {
                commands::e2m::run_labels_cardinality(&targets, output).await?;
            }
            E2mCmd::Limits => {
                commands::e2m::run_limits(&targets, output).await?;
            }
        },

        Commands::RecordingRules { cmd } => match cmd {
            RecordingRulesCmd::List => {
                commands::recording_rules::run_list(&targets, output).await?;
            }
            RecordingRulesCmd::Get { id } => {
                commands::recording_rules::run_get(&targets, &id, output).await?;
            }
            RecordingRulesCmd::Create { from_file } => {
                confirm_destructive("Create a new recording rule group?", yes, agent_mode)?;
                commands::recording_rules::run_create(&targets, &from_file, output).await?;
            }
            RecordingRulesCmd::Update { from_file, id } => {
                confirm_destructive(
                    &format!("Update recording rule group '{id}'?"),
                    yes,
                    agent_mode,
                )?;
                commands::recording_rules::run_update(&targets, &id, &from_file, output).await?;
            }
            RecordingRulesCmd::Delete { id } => {
                confirm_destructive(
                    &format!("Delete recording rule group '{id}'?"),
                    yes,
                    agent_mode,
                )?;
                commands::recording_rules::run_delete(&targets, &id).await?;
            }
        },

        Commands::ParsingRules { cmd } => match cmd {
            ParsingRulesCmd::List => {
                commands::parsing_rules::run_list(&targets, output).await?;
            }
            ParsingRulesCmd::Get { id } => {
                commands::parsing_rules::run_get(&targets, &id, output).await?;
            }
            ParsingRulesCmd::Create { from_file } => {
                confirm_destructive("Create a new parsing rule?", yes, agent_mode)?;
                commands::parsing_rules::run_create(&targets, &from_file, output).await?;
            }
            ParsingRulesCmd::Update { from_file, id } => {
                confirm_destructive(&format!("Update parsing rule '{id}'?"), yes, agent_mode)?;
                commands::parsing_rules::run_update(&targets, &id, &from_file, output).await?;
            }
            ParsingRulesCmd::Delete { id } => {
                confirm_destructive(&format!("Delete parsing rule '{id}'?"), yes, agent_mode)?;
                commands::parsing_rules::run_delete(&targets, &id).await?;
            }
            ParsingRulesCmd::BulkDelete { ids } => {
                confirm_destructive("Bulk delete parsing rules?", yes, agent_mode)?;
                commands::parsing_rules::run_bulk_delete(&targets, &ids).await?;
            }
            ParsingRulesCmd::UsageLimits => {
                commands::parsing_rules::run_usage_limits(&targets, output).await?;
            }
        },

        Commands::Enrichments { cmd } => match cmd {
            EnrichmentsCmd::List => {
                commands::enrichments::run_list(&targets, output).await?;
            }
            EnrichmentsCmd::Add { from_file } => {
                confirm_destructive("Add enrichment rules?", yes, agent_mode)?;
                commands::enrichments::run_add(&targets, &from_file, output).await?;
            }
            EnrichmentsCmd::Remove { from_file } => {
                confirm_destructive("Remove enrichment rules?", yes, agent_mode)?;
                commands::enrichments::run_remove(&targets, &from_file, output).await?;
            }
            EnrichmentsCmd::Overwrite { from_file } => {
                confirm_destructive("Overwrite enrichment rules?", yes, agent_mode)?;
                commands::enrichments::run_overwrite(&targets, &from_file, output).await?;
            }
            EnrichmentsCmd::Limit => {
                commands::enrichments::run_limit(&targets, output).await?;
            }
            EnrichmentsCmd::Settings => {
                commands::enrichments::run_settings(&targets, output).await?;
            }
            EnrichmentsCmd::Custom { cmd } => match cmd {
                CustomEnrichmentsCmd::List => {
                    commands::custom_enrichments::run_list(&targets, output).await?;
                }
                CustomEnrichmentsCmd::Get { id } => {
                    commands::custom_enrichments::run_get(&targets, &id, output).await?;
                }
                CustomEnrichmentsCmd::Create { from_file } => {
                    confirm_destructive("Create a new custom enrichment?", yes, agent_mode)?;
                    commands::custom_enrichments::run_create(&targets, &from_file, output).await?;
                }
                CustomEnrichmentsCmd::Update { from_file } => {
                    confirm_destructive("Update custom enrichment?", yes, agent_mode)?;
                    commands::custom_enrichments::run_update(&targets, &from_file, output).await?;
                }
                CustomEnrichmentsCmd::Delete { id } => {
                    confirm_destructive(
                        &format!("Delete custom enrichment '{id}'?"),
                        yes,
                        agent_mode,
                    )?;
                    commands::custom_enrichments::run_delete(&targets, &id).await?;
                }
                CustomEnrichmentsCmd::Search { id, query } => {
                    commands::custom_enrichments::run_search(&targets, &id, &query, output).await?;
                }
            },
        },

        Commands::Integrations { cmd } => match cmd {
            IntegrationsCmd::List => {
                commands::integrations::run_list(&targets, output).await?;
            }
            IntegrationsCmd::Get { id } => {
                commands::integrations::run_get(&targets, &id, output).await?;
            }
            IntegrationsCmd::Definition { id } => {
                commands::integrations::run_definition(&targets, &id, output).await?;
            }
            IntegrationsCmd::Deployed { id } => {
                commands::integrations::run_deployed(&targets, &id, output).await?;
            }
            IntegrationsCmd::Create { from_file } => {
                confirm_destructive("Create a new integration?", yes, agent_mode)?;
                commands::integrations::run_create(&targets, &from_file, output).await?;
            }
            IntegrationsCmd::Update { id, from_file } => {
                confirm_destructive(&format!("Update integration '{id}'?"), yes, agent_mode)?;
                commands::integrations::run_update(&targets, &id, &from_file, output).await?;
            }
            IntegrationsCmd::Delete { id } => {
                confirm_destructive(&format!("Delete integration '{id}'?"), yes, agent_mode)?;
                commands::integrations::run_delete(&targets, &id).await?;
            }
            IntegrationsCmd::Test { from_file } => {
                confirm_destructive("Test integration?", yes, agent_mode)?;
                commands::integrations::run_test(&targets, &from_file, output).await?;
            }
            IntegrationsCmd::Template => {
                commands::integrations::run_template(&targets, output).await?;
            }
            IntegrationsCmd::Extensions { cmd } => match cmd {
                ExtensionsCmd::List => {
                    commands::extensions::run_list(&targets, output).await?;
                }
                ExtensionsCmd::Get { id } => {
                    commands::extensions::run_get(&targets, &id, output).await?;
                }
                ExtensionsCmd::Deployed => {
                    commands::extensions::run_deployed(&targets, output).await?;
                }
                ExtensionsCmd::Deploy { from_file } => {
                    confirm_destructive("Deploy extension?", yes, agent_mode)?;
                    commands::extensions::run_deploy(&targets, &from_file, output).await?;
                }
                ExtensionsCmd::Update { from_file } => {
                    confirm_destructive("Update extension?", yes, agent_mode)?;
                    commands::extensions::run_update(&targets, &from_file, output).await?;
                }
                ExtensionsCmd::Undeploy { from_file } => {
                    confirm_destructive("Undeploy extension?", yes, agent_mode)?;
                    commands::extensions::run_undeploy(&targets, &from_file, output).await?;
                }
            },
            IntegrationsCmd::ContextualData { cmd } => match cmd {
                ContextualDataCmd::List => {
                    commands::contextual_data::run_list(&targets, output).await?;
                }
                ContextualDataCmd::Get { id } => {
                    commands::contextual_data::run_get(&targets, &id, output).await?;
                }
                ContextualDataCmd::Create { from_file } => {
                    confirm_destructive("Create contextual data integration?", yes, agent_mode)?;
                    commands::contextual_data::run_create(&targets, &from_file, output).await?;
                }
                ContextualDataCmd::Update { id, from_file } => {
                    confirm_destructive(
                        &format!("Update contextual data '{id}'?"),
                        yes,
                        agent_mode,
                    )?;
                    commands::contextual_data::run_update(&targets, &id, &from_file, output)
                        .await?;
                }
                ContextualDataCmd::Delete { id } => {
                    confirm_destructive(
                        &format!("Delete contextual data '{id}'?"),
                        yes,
                        agent_mode,
                    )?;
                    commands::contextual_data::run_delete(&targets, &id).await?;
                }
                ContextualDataCmd::Definition { id } => {
                    commands::contextual_data::run_definition(&targets, &id, output).await?;
                }
                ContextualDataCmd::Test { id } => {
                    commands::contextual_data::run_test(&targets, &id, output).await?;
                }
            },
        },

        Commands::Webhooks { cmd } => match cmd {
            WebhooksCmd::List => {
                commands::webhooks::run_list(&targets, output).await?;
            }
            WebhooksCmd::Get { id } => {
                commands::webhooks::run_get(&targets, &id, output).await?;
            }
            WebhooksCmd::Create { from_file } => {
                confirm_destructive("Create a new webhook?", yes, agent_mode)?;
                commands::webhooks::run_create(&targets, &from_file, output).await?;
            }
            WebhooksCmd::Update { id, from_file } => {
                confirm_destructive(&format!("Update webhook '{id}'?"), yes, agent_mode)?;
                commands::webhooks::run_update(&targets, &id, &from_file, output).await?;
            }
            WebhooksCmd::Delete { id } => {
                confirm_destructive(&format!("Delete webhook '{id}'?"), yes, agent_mode)?;
                commands::webhooks::run_delete(&targets, &id).await?;
            }
            WebhooksCmd::Test { id } => {
                confirm_destructive(&format!("Test webhook '{id}'?"), yes, agent_mode)?;
                commands::webhooks::run_test(&targets, &id, output).await?;
            }
            WebhooksCmd::Types => {
                commands::webhooks::run_types(&targets, output).await?;
            }
            WebhooksCmd::Actions { cmd } => match cmd {
                ActionsCmd::List => {
                    commands::actions::run_list(&targets, output).await?;
                }
                ActionsCmd::Get { id } => {
                    commands::actions::run_get(&targets, &id, output).await?;
                }
                ActionsCmd::Create { from_file } => {
                    confirm_destructive("Create a new webhook action?", yes, agent_mode)?;
                    commands::actions::run_create(&targets, &from_file, output).await?;
                }
                ActionsCmd::Update { from_file } => {
                    confirm_destructive("Update webhook action?", yes, agent_mode)?;
                    commands::actions::run_update(&targets, &from_file, output).await?;
                }
                ActionsCmd::Delete { id } => {
                    confirm_destructive(
                        &format!("Delete webhook action '{id}'?"),
                        yes,
                        agent_mode,
                    )?;
                    commands::actions::run_delete(&targets, &id).await?;
                }
                ActionsCmd::Batch { from_file } => {
                    confirm_destructive("Batch execute webhook actions?", yes, agent_mode)?;
                    commands::actions::run_batch(&targets, &from_file, output).await?;
                }
                ActionsCmd::Reorder { from_file } => {
                    confirm_destructive("Reorder webhook actions?", yes, agent_mode)?;
                    commands::actions::run_reorder(&targets, &from_file, output).await?;
                }
            },
        },

        Commands::Views { cmd } => match cmd {
            ViewsCmd::List => {
                commands::views::run_list(&targets, output).await?;
            }
            ViewsCmd::Get { id } => {
                commands::views::run_get(&targets, &id, output).await?;
            }
            ViewsCmd::Create { from_file } => {
                confirm_destructive("Create a new view?", yes, agent_mode)?;
                commands::views::run_create(&targets, &from_file, output).await?;
            }
            ViewsCmd::Update { id, from_file } => {
                confirm_destructive(&format!("Update view '{id}'?"), yes, agent_mode)?;
                commands::views::run_update(&targets, &id, &from_file, output).await?;
            }
            ViewsCmd::Delete { id } => {
                confirm_destructive(&format!("Delete view '{id}'?"), yes, agent_mode)?;
                commands::views::run_delete(&targets, &id).await?;
            }
            ViewsCmd::Folders { cmd } => match cmd {
                ViewFoldersCmd::List => {
                    commands::views::run_folders_list(&targets, output).await?;
                }
                ViewFoldersCmd::Get { id } => {
                    commands::views::run_folders_get(&targets, &id, output).await?;
                }
                ViewFoldersCmd::Create { from_file } => {
                    confirm_destructive("Create a new view folder?", yes, agent_mode)?;
                    commands::views::run_folders_create(&targets, &from_file, output).await?;
                }
                ViewFoldersCmd::Update { id, from_file } => {
                    confirm_destructive(&format!("Update view folder '{id}'?"), yes, agent_mode)?;
                    commands::views::run_folders_update(&targets, &id, &from_file, output).await?;
                }
                ViewFoldersCmd::Delete { id } => {
                    confirm_destructive(&format!("Delete view folder '{id}'?"), yes, agent_mode)?;
                    commands::views::run_folders_delete(&targets, &id).await?;
                }
            },
        },

        Commands::Iam { cmd } => match cmd {
            IamCmd::ApiKeys { cmd } => match cmd {
                ApiKeysCmd::List => {
                    commands::api_keys::run_list(&targets, output).await?;
                }
                ApiKeysCmd::Get { id } => {
                    commands::api_keys::run_get(&targets, &id, output).await?;
                }
                ApiKeysCmd::Create { from_file } => {
                    confirm_destructive("Create a new API key?", yes, agent_mode)?;
                    commands::api_keys::run_create(&targets, &from_file, output).await?;
                }
                ApiKeysCmd::Update { from_file, id } => {
                    confirm_destructive(&format!("Update API key '{id}'?"), yes, agent_mode)?;
                    commands::api_keys::run_update(&targets, &id, &from_file, output).await?;
                }
                ApiKeysCmd::Delete { id } => {
                    confirm_destructive(&format!("Delete API key '{id}'?"), yes, agent_mode)?;
                    commands::api_keys::run_delete(&targets, &id).await?;
                }
                ApiKeysCmd::SendDataKeys => {
                    commands::api_keys::run_send_data_keys(&targets, output).await?;
                }
                ApiKeysCmd::Admin { cmd } => match cmd {
                    ApiKeysAdminCmd::List => {
                        commands::api_keys::run_admin_list(&targets, output).await?;
                    }
                    ApiKeysAdminCmd::Delete { ids } => {
                        confirm_destructive("Bulk delete API keys?", yes, agent_mode)?;
                        commands::api_keys::run_admin_delete(&targets, &ids).await?;
                    }
                    ApiKeysAdminCmd::SetStatus { ids, active } => {
                        confirm_destructive(
                            &format!("Set API key status to active={active}?"),
                            yes,
                            agent_mode,
                        )?;
                        commands::api_keys::run_admin_set_status(&targets, &ids, active).await?;
                    }
                },
            },
            IamCmd::Roles { cmd } => match cmd {
                RolesCmd::List => {
                    commands::roles::run_list(&targets, output).await?;
                }
                RolesCmd::Get { id } => {
                    commands::roles::run_get(&targets, &id, output).await?;
                }
                RolesCmd::Create { from_file } => {
                    confirm_destructive("Create a new custom role?", yes, agent_mode)?;
                    commands::roles::run_create(&targets, &from_file, output).await?;
                }
                RolesCmd::Update { from_file, id } => {
                    confirm_destructive(&format!("Update role '{id}'?"), yes, agent_mode)?;
                    commands::roles::run_update(&targets, &id, &from_file, output).await?;
                }
                RolesCmd::Delete { id } => {
                    confirm_destructive(&format!("Delete role '{id}'?"), yes, agent_mode)?;
                    commands::roles::run_delete(&targets, &id).await?;
                }
                RolesCmd::System => {
                    commands::roles::run_system(&targets, output).await?;
                }
            },
            IamCmd::Scopes { cmd } => match cmd {
                ScopesCmd::List => {
                    commands::scopes::run_list(&targets, output).await?;
                }
                ScopesCmd::Get { id } => {
                    commands::scopes::run_get(&targets, &id, output).await?;
                }
                ScopesCmd::Create { from_file } => {
                    confirm_destructive("Create a new scope?", yes, agent_mode)?;
                    commands::scopes::run_create(&targets, &from_file, output).await?;
                }
                ScopesCmd::Update { from_file } => {
                    confirm_destructive("Update scope?", yes, agent_mode)?;
                    commands::scopes::run_update(&targets, &from_file, output).await?;
                }
                ScopesCmd::Delete { id } => {
                    confirm_destructive(&format!("Delete scope '{id}'?"), yes, agent_mode)?;
                    commands::scopes::run_delete(&targets, &id).await?;
                }
            },
            IamCmd::Users { cmd } => match cmd {
                UsersCmd::Search {
                    query,
                    status,
                    page_size,
                    page_token,
                } => {
                    commands::users::run_search(
                        &targets,
                        query.as_deref(),
                        status.as_deref(),
                        page_size.as_deref(),
                        page_token.as_deref(),
                        output,
                    )
                    .await?;
                }
                UsersCmd::Get { user_id } => {
                    commands::users::run_get(&targets, &user_id, output).await?;
                }
                UsersCmd::Create { from_file } => {
                    confirm_destructive("Create user(s)?", yes, agent_mode)?;
                    commands::users::run_create(&targets, &from_file, output).await?;
                }
                UsersCmd::Update { from_file } => {
                    confirm_destructive("Update user(s)?", yes, agent_mode)?;
                    commands::users::run_update(&targets, &from_file, output).await?;
                }
                UsersCmd::SetStatus { user_ids, status } => {
                    confirm_destructive(
                        &format!("Set user status to '{status}'?"),
                        yes,
                        agent_mode,
                    )?;
                    commands::users::run_set_status(&targets, &user_ids, &status).await?;
                }
            },
            IamCmd::TeamGroups { cmd } => match cmd {
                TeamGroupsCmd::List {} => {
                    commands::team_groups::run_list(&targets, output).await?;
                }
                TeamGroupsCmd::Get { id } => {
                    commands::team_groups::run_get(&targets, &id, output).await?;
                }
                TeamGroupsCmd::GetByName { name } => {
                    commands::team_groups::run_get_by_name(&targets, &name, output).await?;
                }
                TeamGroupsCmd::Users { group_id } => {
                    commands::team_groups::run_users(&targets, &group_id, output).await?;
                }
                TeamGroupsCmd::Create { from_file } => {
                    confirm_destructive("Create a new team group?", yes, agent_mode)?;
                    commands::team_groups::run_create(&targets, &from_file, output).await?;
                }
                TeamGroupsCmd::Update { from_file, id } => {
                    confirm_destructive(&format!("Update team group '{id}'?"), yes, agent_mode)?;
                    commands::team_groups::run_update(&targets, &id, &from_file, output).await?;
                }
                TeamGroupsCmd::Delete { id } => {
                    confirm_destructive(&format!("Delete team group '{id}'?"), yes, agent_mode)?;
                    commands::team_groups::run_delete(&targets, &id).await?;
                }
            },
            IamCmd::IpAccess { cmd } => match cmd {
                IpAccessCmd::Get => {
                    commands::ip_access::run_get(&targets, output).await?;
                }
                IpAccessCmd::Create { from_file } => {
                    confirm_destructive("Create IP access rules?", yes, agent_mode)?;
                    commands::ip_access::run_create(&targets, &from_file, output).await?;
                }
                IpAccessCmd::Update { from_file } => {
                    confirm_destructive("Update IP access rules?", yes, agent_mode)?;
                    commands::ip_access::run_update(&targets, &from_file, output).await?;
                }
                IpAccessCmd::Delete => {
                    confirm_destructive(
                        "Delete all IP access rules? This removes all IP restrictions.",
                        yes,
                        agent_mode,
                    )?;
                    commands::ip_access::run_delete(&targets).await?;
                }
            },
        },

        Commands::DataArchive { cmd } => match cmd {
            DataArchiveCmd::Metrics { cmd } => match cmd {
                DataArchiveMetricsCmd::Get => {
                    commands::data_archive::run_metrics_get(&targets, output).await?;
                }
                DataArchiveMetricsCmd::Create { from_file } => {
                    confirm_destructive("Create metrics archive configuration?", yes, agent_mode)?;
                    commands::data_archive::run_metrics_create(&targets, &from_file, output)
                        .await?;
                }
                DataArchiveMetricsCmd::Update { from_file } => {
                    confirm_destructive("Update metrics archive configuration?", yes, agent_mode)?;
                    commands::data_archive::run_metrics_update(&targets, &from_file, output)
                        .await?;
                }
                DataArchiveMetricsCmd::Enable => {
                    confirm_destructive("Enable metrics archiving?", yes, agent_mode)?;
                    commands::data_archive::run_metrics_enable(&targets).await?;
                }
                DataArchiveMetricsCmd::Disable => {
                    confirm_destructive("Disable metrics archiving?", yes, agent_mode)?;
                    commands::data_archive::run_metrics_disable(&targets).await?;
                }
                DataArchiveMetricsCmd::Validate { from_file } => {
                    commands::data_archive::run_metrics_validate(&targets, &from_file, output)
                        .await?;
                }
            },
            DataArchiveCmd::Logs { cmd } => match cmd {
                DataArchiveLogsCmd::Get => {
                    commands::data_archive::run_logs_get(&targets, output).await?;
                }
                DataArchiveLogsCmd::Set { from_file } => {
                    confirm_destructive("Set logs archive target?", yes, agent_mode)?;
                    commands::data_archive::run_logs_set(&targets, &from_file, output).await?;
                }
            },
        },

        Commands::Slos { cmd } => match cmd {
            SlosCmd::List => {
                commands::slos::run_list(&targets, output).await?;
            }
            SlosCmd::Get { id } => {
                commands::slos::run_get(&targets, &id, output).await?;
            }
            SlosCmd::Create { from_file } => {
                confirm_destructive("Create a new SLO?", yes, agent_mode)?;
                commands::slos::run_create(&targets, &from_file, output).await?;
            }
            SlosCmd::Update { from_file } => {
                confirm_destructive("Update SLO?", yes, agent_mode)?;
                commands::slos::run_update(&targets, &from_file, output).await?;
            }
            SlosCmd::Delete { id } => {
                confirm_destructive(&format!("Delete SLO '{id}'?"), yes, agent_mode)?;
                commands::slos::run_delete(&targets, &id).await?;
            }
        },

        Commands::SearchFields {
            text,
            search_type,
            dataset,
            limit,
            offset,
        } => match search_type {
            SearchType::Semantic => {
                let dataset_str = match dataset {
                    SearchByValueDataset::Logs => "logs",
                    SearchByValueDataset::Spans => "spans",
                    SearchByValueDataset::All => {
                        bail!("--dataset all is only valid with -s value");
                    }
                };
                commands::search_fields::run(&targets, &text, dataset_str, limit, output).await?;
            }
            SearchType::Value => {
                let dataset_str = match dataset {
                    SearchByValueDataset::Logs => "logs",
                    SearchByValueDataset::Spans => "spans",
                    SearchByValueDataset::All => "all",
                };
                commands::search_by_value::run(&targets, &text, dataset_str, limit, offset, output)
                    .await?;
            }
        },

        Commands::Olly { cmd } => match cmd {
            OllyCmd::Ask {
                message,
                chat_id,
                model,
                timeout,
            } => {
                commands::olly::run_ask(
                    &targets,
                    &message,
                    chat_id.as_deref(),
                    &model,
                    timeout,
                    output,
                )
                .await?;
            }
            OllyCmd::Artifacts { cmd } => match cmd {
                OllyArtifactsCmd::List => {
                    commands::olly::run_artifacts_list(&targets, output).await?;
                }
                OllyArtifactsCmd::Get { artifact_id } => {
                    commands::olly::run_artifacts_get(
                        &targets,
                        &artifact_id,
                        output,
                        max_direct,
                        &temp_dir,
                    )
                    .await?;
                }
            },
        },
    }

    Ok(())
}