slack-rs 0.1.70

A Slack CLI tool with OAuth authentication, profile management, and API access
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
//! CLI command routing and handlers

mod context;
mod handlers;
mod help;
pub mod introspection;

pub use context::CliContext;
pub use handlers::{
    handle_export_command, handle_import_command, run_api_call, run_auth_login, run_install_skill,
};
pub use introspection::{
    generate_commands_list, generate_help, generate_schema, CommandDef, CommandsListResponse,
    HelpResponse, SchemaResponse,
};

use crate::api::{ApiClient, CommandResponse};
use crate::commands;
use crate::commands::ConversationSelector;
use crate::debug;
use crate::profile::{
    create_token_store, default_config_path, load_config, make_token_key, resolve_profile_full,
    TokenStore, TokenType,
};
use serde_json::Value;

/// Resolve token with priority: SLACK_TOKEN env > token store
///
/// # Arguments
/// * `slack_token_env` - Value of SLACK_TOKEN environment variable (None if unset)
/// * `token_store` - Token store to retrieve tokens from
/// * `token_key` - Key to use for token store lookup
/// * `fallback_token_key` - Optional fallback key (e.g., bot token when user token not found)
/// * `explicit_request` - Whether the token type was explicitly requested (via --token-type or default_token_type)
///
/// # Returns
/// * `Ok(token)` - Successfully resolved token
/// * `Err(message)` - Token resolution failed
///
/// # Token Resolution Priority
/// 1. SLACK_TOKEN environment variable (if set, bypasses token store)
/// 2. Token store with primary token_key
/// 3. Token store with fallback_token_key (only if not explicit_request)
/// 4. Error if no token found
#[allow(dead_code)]
pub fn resolve_token_for_wrapper(
    slack_token_env: Option<String>,
    token_store: &dyn TokenStore,
    token_key: &str,
    fallback_token_key: Option<&str>,
    explicit_request: bool,
) -> Result<String, String> {
    // Priority 1: SLACK_TOKEN environment variable
    if let Some(env_token) = slack_token_env {
        return Ok(env_token);
    }

    // Priority 2: Token store with primary key
    if let Ok(token) = token_store.get(token_key) {
        return Ok(token);
    }

    // Priority 3: Fallback token (only if not explicit_request)
    if !explicit_request {
        if let Some(fallback_key) = fallback_token_key {
            if let Ok(token) = token_store.get(fallback_key) {
                eprintln!("Warning: Primary token not found, falling back to alternative token");
                return Ok(token);
            }
        }
    }

    // Priority 4: Error
    if explicit_request {
        Err(
            "No token found for explicitly requested token type. Set SLACK_TOKEN environment variable or run 'slack login' to obtain a token.".to_string()
        )
    } else {
        Err(
            "No token found. Set SLACK_TOKEN environment variable or run 'slack login' to obtain a token.".to_string()
        )
    }
}

/// Get API client for a profile with optional token type selection
///
/// # Arguments
/// * `profile_name` - Optional profile name (defaults to "default")
/// * `token_type` - Optional token type (bot/user). If None, uses profile default or bot fallback
///
/// # Token Resolution Priority
/// 1. SLACK_TOKEN environment variable (if set, bypasses token store)
/// 2. CLI flag token_type parameter (if provided)
/// 3. Profile's default_token_type (if set)
/// 4. Try user token first, fall back to bot token
pub async fn get_api_client_with_token_type(
    profile_name: Option<String>,
    token_type: Option<TokenType>,
) -> Result<ApiClient, String> {
    // Check for SLACK_TOKEN environment variable first
    if let Ok(env_token) = std::env::var("SLACK_TOKEN") {
        return Ok(ApiClient::with_token(env_token));
    }

    let profile_name = profile_name.unwrap_or_else(|| "default".to_string());
    let config_path = default_config_path().map_err(|e| e.to_string())?;
    let config = load_config(&config_path).map_err(|e| e.to_string())?;

    let profile = config
        .get(&profile_name)
        .ok_or_else(|| format!("Profile '{}' not found", profile_name))?;

    let token_store = create_token_store().map_err(|e| e.to_string())?;

    // Resolve token type: CLI flag > profile default > try user first with bot fallback
    let resolved_token_type = token_type.or(profile.default_token_type);

    let bot_token_key = make_token_key(&profile.team_id, &profile.user_id);
    let user_token_key = format!("{}:{}:user", profile.team_id, profile.user_id);

    let token = match resolved_token_type {
        Some(TokenType::Bot) => {
            // Explicitly requested bot token
            token_store
                .get(&bot_token_key)
                .map_err(|e| format!("Failed to get bot token: {}", e))?
        }
        Some(TokenType::User) => {
            // Explicitly requested user token
            token_store
                .get(&user_token_key)
                .map_err(|e| format!("Failed to get user token: {}", e))?
        }
        None => {
            // No explicit preference, try user token first (for APIs that require user scope)
            match token_store.get(&user_token_key) {
                Ok(user_token) => user_token,
                Err(_) => {
                    // Fall back to bot token
                    token_store
                        .get(&bot_token_key)
                        .map_err(|e| format!("Failed to get token: {}", e))?
                }
            }
        }
    };

    Ok(ApiClient::with_token(token))
}

/// Get API client for a profile (legacy function, maintains backward compatibility)
#[allow(dead_code)]
pub async fn get_api_client(profile_name: Option<String>) -> Result<ApiClient, String> {
    get_api_client_with_token_type(profile_name, None).await
}

/// Check if a flag exists in args
pub fn has_flag(args: &[String], flag: &str) -> bool {
    args.iter().any(|arg| arg == flag)
}

/// Determine if output should be raw based on SLACKRS_OUTPUT environment variable and --raw flag
///
/// # Arguments
/// * `args` - Command line arguments
///
/// # Returns
/// * `true` if output should be raw (without envelope)
/// * `false` if output should include envelope
///
/// # Priority
/// 1. --raw flag (highest priority)
/// 2. SLACKRS_OUTPUT environment variable ("raw" or "envelope")
/// 3. Default to envelope (false)
pub fn should_output_raw(args: &[String]) -> bool {
    // Priority 1: --raw flag always wins
    if has_flag(args, "--raw") {
        return true;
    }

    // Priority 2: Check SLACKRS_OUTPUT environment variable
    if let Ok(output_mode) = std::env::var("SLACKRS_OUTPUT") {
        return output_mode.trim().to_lowercase() == "raw";
    }

    // Priority 3: Default to envelope (false)
    false
}

/// Check if error message indicates non-interactive mode failure
pub fn is_non_interactive_error(error_msg: &str) -> bool {
    error_msg.contains("Non-interactive mode error")
        || error_msg.contains("Use --yes flag to confirm in non-interactive mode")
}

/// Wrap response with unified envelope including metadata
#[allow(dead_code)]
pub async fn wrap_with_envelope(
    response: Value,
    method: &str,
    command: &str,
    profile_name: Option<String>,
) -> Result<CommandResponse, String> {
    wrap_with_envelope_and_token_type(response, method, command, profile_name, None).await
}

/// Wrap response with unified envelope including metadata and explicit token type
pub async fn wrap_with_envelope_and_token_type(
    response: Value,
    method: &str,
    command: &str,
    profile_name: Option<String>,
    explicit_token_type: Option<TokenType>,
) -> Result<CommandResponse, String> {
    let profile_name_str = profile_name.unwrap_or_else(|| "default".to_string());
    let config_path = default_config_path().map_err(|e| e.to_string())?;
    let profile = resolve_profile_full(&config_path, &profile_name_str)
        .map_err(|e| format!("Failed to resolve profile '{}': {}", profile_name_str, e))?;

    // Resolve token type for metadata
    let token_type_str = if let Some(explicit) = explicit_token_type {
        // If explicitly specified via --token-type, use that
        Some(explicit.to_string())
    } else if std::env::var("SLACK_TOKEN").is_ok() {
        // If using SLACK_TOKEN, use profile's default_token_type if set, otherwise "bot"
        Some(
            profile
                .default_token_type
                .map(|t| t.to_string())
                .unwrap_or_else(|| "bot".to_string()),
        )
    } else {
        // Resolve from token store (check which token exists)
        let token_store = create_token_store().map_err(|e| e.to_string())?;
        let bot_token_key = make_token_key(&profile.team_id, &profile.user_id);
        let user_token_key = format!("{}:{}:user", profile.team_id, profile.user_id);

        // Try to determine which token was used based on default_token_type
        let resolved_type = profile.default_token_type.or_else(|| {
            // If no default, check which token exists (try user first, then bot)
            if token_store.get(&user_token_key).is_ok() {
                Some(TokenType::User)
            } else if token_store.get(&bot_token_key).is_ok() {
                Some(TokenType::Bot)
            } else {
                None
            }
        });

        resolved_type.map(|t| t.to_string())
    };

    Ok(CommandResponse::with_token_type(
        response,
        Some(profile_name_str),
        profile.team_id,
        profile.user_id,
        method.to_string(),
        command.to_string(),
        token_type_str,
    ))
}

/// Resolve profile name with priority: --profile flag > SLACK_PROFILE env > "default"
///
/// This function implements the unified profile selection logic across all CLI commands.
/// It searches for `--profile` in any position within the args array, supporting both
/// `--profile=name` and `--profile name` formats.
///
/// # Arguments
/// * `args` - Command line arguments (including subcommands and flags)
///
/// # Returns
/// Profile name resolved according to priority rules
///
/// # Priority
/// 1. `--profile` flag from command line (either format)
/// 2. `SLACK_PROFILE` environment variable
/// 3. "default" as fallback
pub fn resolve_profile_name(args: &[String]) -> String {
    // Priority 1: Check for --profile flag in args
    if let Some(profile) = get_option(args, "--profile=") {
        return profile;
    }

    // Priority 2: Check SLACK_PROFILE environment variable
    if let Ok(profile) = std::env::var("SLACK_PROFILE") {
        return profile;
    }

    // Priority 3: Default to "default"
    "default".to_string()
}

/// Get option value from args
/// Supports both --key=value and --key value formats
/// When using space-separated format, value must not start with '-'
pub fn get_option(args: &[String], prefix: &str) -> Option<String> {
    // First try --key=value format
    if let Some(value) = args
        .iter()
        .find(|arg| arg.starts_with(prefix))
        .and_then(|arg| arg.strip_prefix(prefix))
        .map(|s| s.to_string())
    {
        return Some(value);
    }

    // Then try --key value format (space-separated)
    // Extract the flag name without the '=' suffix
    let flag = prefix.strip_suffix('=').unwrap_or(prefix);
    if let Some(pos) = args.iter().position(|arg| arg == flag) {
        if let Some(value) = args.get(pos + 1) {
            // Only treat as value if it doesn't start with '-'
            if !value.starts_with('-') {
                return Some(value.clone());
            }
        }
    }

    None
}

/// Parse token type from command line arguments
/// Supports both --token-type=VALUE and --token-type VALUE formats
pub fn parse_token_type(args: &[String]) -> Result<Option<TokenType>, String> {
    // First try --token-type=VALUE format
    if let Some(token_type_str) = get_option(args, "--token-type=") {
        return token_type_str
            .parse::<TokenType>()
            .map(Some)
            .map_err(|e| e.to_string());
    }

    // Then try --token-type VALUE format (space-separated)
    if let Some(pos) = args.iter().position(|arg| arg == "--token-type") {
        if let Some(value) = args.get(pos + 1) {
            return value
                .parse::<TokenType>()
                .map(Some)
                .map_err(|e| e.to_string());
        } else {
            return Err("--token-type requires a value (bot or user)".to_string());
        }
    }

    Ok(None)
}

pub async fn run_search(args: &[String]) -> Result<(), String> {
    let query = args[2].clone();
    let count = get_option(args, "--count=").and_then(|s| s.parse().ok());
    let page = get_option(args, "--page=").and_then(|s| s.parse().ok());
    let sort = get_option(args, "--sort=");
    let sort_dir = get_option(args, "--sort_dir=");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let raw = should_output_raw(args);

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;
    let response = commands::search(&client, query, count, page, sort, sort_dir)
        .await
        .map_err(|e| e.to_string())?;

    // Display error guidance if response contains a known error
    crate::api::display_wrapper_error_guidance(&response);

    // Output with or without envelope
    let output = if raw {
        serde_json::to_string_pretty(&response).unwrap()
    } else {
        let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
        let wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "search.messages",
            "search",
            Some(profile_name),
            token_type,
        )
        .await?;
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

/// Get all options with a specific prefix from args
/// Supports both --key=value and --key value formats (can be mixed)
/// When using space-separated format, value must not start with '-'
pub fn get_all_options(args: &[String], prefix: &str) -> Vec<String> {
    let mut results = Vec::new();

    // Collect --key=value format
    results.extend(
        args.iter()
            .filter(|arg| arg.starts_with(prefix))
            .filter_map(|arg| arg.strip_prefix(prefix))
            .map(|s| s.to_string()),
    );

    // Collect --key value format (space-separated)
    let flag = prefix.strip_suffix('=').unwrap_or(prefix);
    let mut i = 0;
    while i < args.len() {
        if args[i] == flag {
            if let Some(value) = args.get(i + 1) {
                // Only treat as value if it doesn't start with '-'
                if !value.starts_with('-') {
                    results.push(value.clone());
                    i += 2; // Skip both flag and value
                    continue;
                }
            }
        }
        i += 1;
    }

    results
}

pub async fn run_conv_list(args: &[String]) -> Result<(), String> {
    // Check for --help flag before API call
    if has_flag(args, "--help") || has_flag(args, "-h") {
        print_conv_usage(&args[0]);
        return Ok(());
    }

    let types = get_option(args, "--types=");
    let include_private = has_flag(args, "--include-private");
    let all = has_flag(args, "--all");
    let limit = get_option(args, "--limit=").and_then(|s| s.parse().ok());
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let filter_strings = get_all_options(args, "--filter=");
    let raw = should_output_raw(args);

    // Validate: --types is mutually exclusive with --include-private and --all
    if types.is_some() && (include_private || all) {
        return Err("Error: --types cannot be used with --include-private or --all".to_string());
    }

    // Resolve types based on flags
    let resolved_types = if let Some(explicit_types) = types {
        // User explicitly specified types
        Some(explicit_types)
    } else if all {
        // --all flag: include all conversation types
        Some("public_channel,private_channel,im,mpim".to_string())
    } else if include_private {
        // --include-private flag: include public and private channels (same as default now)
        Some("public_channel,private_channel".to_string())
    } else {
        // No flags: use default (public and private channels)
        Some("public_channel,private_channel".to_string())
    };

    // Parse format option (default: json)
    let format = if let Some(fmt_str) = get_option(args, "--format=") {
        commands::OutputFormat::parse(&fmt_str)?
    } else {
        commands::OutputFormat::Json
    };

    // Validate --raw compatibility
    if raw && format != commands::OutputFormat::Json {
        return Err(format!(
            "--raw is only valid with --format json, but got --format {}",
            format
        ));
    }

    // Parse sort options
    let sort_key = if let Some(sort_str) = get_option(args, "--sort=") {
        Some(commands::SortKey::parse(&sort_str)?)
    } else {
        None
    };

    let sort_dir = if let Some(dir_str) = get_option(args, "--sort-dir=") {
        commands::SortDirection::parse(&dir_str)?
    } else {
        commands::SortDirection::default()
    };

    // Parse filters
    let filters: Result<Vec<_>, _> = filter_strings
        .iter()
        .map(|s| commands::ConversationFilter::parse(s))
        .collect();
    let filters = filters.map_err(|e| e.to_string())?;

    // Get debug level from args
    let debug_level = debug::get_debug_level(args);

    // Log debug information if --debug or --trace flag is present
    let token_store_backend = if std::env::var("SLACK_TOKEN").is_ok() {
        "environment"
    } else {
        "file"
    };

    // Resolve actual token type for debug output
    let resolved_token_type = if let Some(explicit) = token_type {
        explicit
    } else {
        // Get profile to check default_token_type
        let config_path = default_config_path().map_err(|e| e.to_string())?;
        let profile = resolve_profile_full(&config_path, &profile_name)
            .map_err(|e| format!("Failed to resolve profile '{}': {}", profile_name, e))?;

        if let Some(default_type) = profile.default_token_type {
            default_type
        } else {
            // Infer from token availability
            let token_store = create_token_store().map_err(|e| e.to_string())?;
            let user_token_key = format!("{}:{}:user", profile.team_id, profile.user_id);
            if token_store.get(&user_token_key).is_ok() {
                TokenType::User
            } else {
                TokenType::Bot
            }
        }
    };

    let endpoint = "https://slack.com/api/conversations.list";

    debug::log_api_context(
        debug_level,
        Some(&profile_name),
        token_store_backend,
        resolved_token_type.as_str(),
        "conversations.list",
        endpoint,
    );

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;
    let mut response = commands::conv_list(&client, resolved_types, limit)
        .await
        .map_err(|e| e.to_string())?;

    // Log error code if present
    debug::log_error_code(
        debug_level,
        &serde_json::to_value(&response).unwrap_or_default(),
    );

    // Display error guidance if response contains a known error
    crate::api::display_wrapper_error_guidance(&response);

    // Apply filters
    commands::apply_filters(&mut response, &filters);

    // Apply sorting if specified
    if let Some(key) = sort_key {
        commands::sort_conversations(&mut response, key, sort_dir);
    }

    // Format output: non-JSON formats bypass raw/envelope logic
    let output = if format != commands::OutputFormat::Json {
        commands::format_response(&response, format)?
    } else if raw {
        serde_json::to_string_pretty(&response).unwrap()
    } else {
        let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
        let wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "conversations.list",
            "conv list",
            Some(profile_name),
            token_type,
        )
        .await?;
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_conv_select(args: &[String]) -> Result<(), String> {
    // Check for --help flag before API call
    if has_flag(args, "--help") || has_flag(args, "-h") {
        print_conv_usage(&args[0]);
        return Ok(());
    }

    let types = get_option(args, "--types=");
    let limit = get_option(args, "--limit=").and_then(|s| s.parse().ok());
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let filter_strings = get_all_options(args, "--filter=");

    // Parse filters
    let filters: Result<Vec<_>, _> = filter_strings
        .iter()
        .map(|s| commands::ConversationFilter::parse(s))
        .collect();
    let filters = filters.map_err(|e| e.to_string())?;

    // Resolve types: default to public_channel,private_channel if not specified
    let resolved_types = types.or(Some("public_channel,private_channel".to_string()));

    let client = get_api_client_with_token_type(Some(profile_name), token_type).await?;
    let mut response = commands::conv_list(&client, resolved_types, limit)
        .await
        .map_err(|e| e.to_string())?;

    // Apply filters
    commands::apply_filters(&mut response, &filters);

    // Extract conversations and present selection
    let items = commands::extract_conversations(&response);
    let selector = commands::StdinSelector;
    let channel_id = selector.select(&items)?;

    println!("{}", channel_id);
    Ok(())
}

pub async fn run_conv_search(args: &[String]) -> Result<(), String> {
    // Check for --help flag before pattern extraction
    if has_flag(args, "--help") || has_flag(args, "-h") {
        print_conv_usage(&args[0]);
        return Ok(());
    }

    // Extract the search pattern (first non-flag argument after "search")
    let pattern = args
        .get(3)
        .filter(|arg| !arg.starts_with("--"))
        .ok_or_else(|| "Search pattern is required".to_string())?
        .clone();

    let types = get_option(args, "--types=");
    let limit = get_option(args, "--limit=").and_then(|s| s.parse().ok());
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let raw = should_output_raw(args);
    let select = has_flag(args, "--select");

    // Parse additional filters from --filter= flags
    let filter_strings = get_all_options(args, "--filter=");

    // Parse format option (default: json)
    let format = if let Some(fmt_str) = get_option(args, "--format=") {
        commands::OutputFormat::parse(&fmt_str)?
    } else {
        commands::OutputFormat::Json
    };

    // Validate --raw compatibility
    if raw && format != commands::OutputFormat::Json {
        return Err(format!(
            "--raw is only valid with --format json, but got --format {}",
            format
        ));
    }

    // Parse sort options
    let sort_key = if let Some(sort_str) = get_option(args, "--sort=") {
        Some(commands::SortKey::parse(&sort_str)?)
    } else {
        None
    };

    let sort_dir = if let Some(dir_str) = get_option(args, "--sort-dir=") {
        commands::SortDirection::parse(&dir_str)?
    } else {
        commands::SortDirection::default()
    };

    // Build filters: inject name:<pattern> filter + any additional filters
    let mut filters: Vec<commands::ConversationFilter> =
        vec![commands::ConversationFilter::Name(pattern)];

    // Parse and add additional filters
    for filter_str in filter_strings {
        filters.push(commands::ConversationFilter::parse(&filter_str).map_err(|e| e.to_string())?);
    }

    // Resolve types: default to public_channel,private_channel if not specified
    let resolved_types = types.or(Some("public_channel,private_channel".to_string()));

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;
    let mut response = commands::conv_list(&client, resolved_types, limit)
        .await
        .map_err(|e| e.to_string())?;

    // Apply filters
    commands::apply_filters(&mut response, &filters);

    // Apply sorting if specified
    if let Some(key) = sort_key {
        commands::sort_conversations(&mut response, key, sort_dir);
    }

    // If --select flag is present, use interactive selection
    if select {
        let items = commands::extract_conversations(&response);
        let selector = commands::StdinSelector;
        let channel_id = selector.select(&items)?;
        println!("{}", channel_id);
        return Ok(());
    }

    // Format output: non-JSON formats bypass raw/envelope logic
    let output = if format != commands::OutputFormat::Json {
        commands::format_response(&response, format)?
    } else if raw {
        serde_json::to_string_pretty(&response).unwrap()
    } else {
        let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
        let wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "conversations.list",
            "conv search",
            Some(profile_name),
            token_type,
        )
        .await?;
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_conv_history(args: &[String]) -> Result<(), String> {
    // Check for --help flag before API call
    if has_flag(args, "--help") || has_flag(args, "-h") {
        print_conv_usage(&args[0]);
        return Ok(());
    }

    let interactive = has_flag(args, "--interactive");

    let channel = if interactive {
        // Use conv_select logic to get channel
        let types = get_option(args, "--types=");
        let profile_name_inner = resolve_profile_name(args);
        let filter_strings = get_all_options(args, "--filter=");

        // Parse filters
        let filters: Result<Vec<_>, _> = filter_strings
            .iter()
            .map(|s| commands::ConversationFilter::parse(s))
            .collect();
        let filters = filters.map_err(|e| e.to_string())?;

        // Resolve types: default to public_channel,private_channel if not specified
        let resolved_types = types.or(Some("public_channel,private_channel".to_string()));

        let token_type_inner = parse_token_type(args)?;
        let client =
            get_api_client_with_token_type(Some(profile_name_inner), token_type_inner).await?;
        let mut response = commands::conv_list(&client, resolved_types, None)
            .await
            .map_err(|e| e.to_string())?;

        // Apply filters
        commands::apply_filters(&mut response, &filters);

        // Extract conversations and present selection
        let items = commands::extract_conversations(&response);
        let selector = commands::StdinSelector;
        selector.select(&items)?
    } else {
        if args.len() < 4 {
            return Err("Channel argument required when --interactive is not used".to_string());
        }
        args[3].clone()
    };

    let limit = get_option(args, "--limit=").and_then(|s| s.parse().ok());
    let oldest = get_option(args, "--oldest=");
    let latest = get_option(args, "--latest=");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let raw = should_output_raw(args);

    // Get debug level from args
    let debug_level = debug::get_debug_level(args);

    // Log debug information if --debug or --trace flag is present
    let token_store_backend = if std::env::var("SLACK_TOKEN").is_ok() {
        "environment"
    } else {
        "file"
    };

    // Resolve actual token type for debug output
    let resolved_token_type = if let Some(explicit) = token_type {
        explicit
    } else {
        let config_path = default_config_path().map_err(|e| e.to_string())?;
        let profile = resolve_profile_full(&config_path, &profile_name)
            .map_err(|e| format!("Failed to resolve profile '{}': {}", profile_name, e))?;

        if let Some(default_type) = profile.default_token_type {
            default_type
        } else {
            let token_store = create_token_store().map_err(|e| e.to_string())?;
            let user_token_key = format!("{}:{}:user", profile.team_id, profile.user_id);
            if token_store.get(&user_token_key).is_ok() {
                TokenType::User
            } else {
                TokenType::Bot
            }
        }
    };

    let endpoint = "https://slack.com/api/conversations.history";

    debug::log_api_context(
        debug_level,
        Some(&profile_name),
        token_store_backend,
        resolved_token_type.as_str(),
        "conversations.history",
        endpoint,
    );

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;
    let response = commands::conv_history(&client, channel, limit, oldest, latest)
        .await
        .map_err(|e| e.to_string())?;

    // Log error code if present
    debug::log_error_code(
        debug_level,
        &serde_json::to_value(&response).unwrap_or_default(),
    );

    // Display error guidance if response contains a known error
    crate::api::display_wrapper_error_guidance(&response);

    // Output with or without envelope
    let output = if raw {
        serde_json::to_string_pretty(&response).unwrap()
    } else {
        let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
        let wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "conversations.history",
            "conv history",
            Some(profile_name),
            token_type,
        )
        .await?;
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_thread_get(args: &[String]) -> Result<(), String> {
    // Check for --help flag before API call
    if has_flag(args, "--help") || has_flag(args, "-h") {
        print_thread_usage(&args[0]);
        return Ok(());
    }

    // Parse required arguments: channel and thread_ts
    if args.len() < 5 {
        return Err("Usage: slack-rs thread get <channel> <thread_ts> [--limit=N] [--inclusive] [--raw] [--profile=NAME] [--token-type=bot|user]".to_string());
    }

    let channel = args[3].clone();
    let thread_ts = args[4].clone();
    let limit = get_option(args, "--limit=").and_then(|s| s.parse().ok());
    let inclusive = has_flag(args, "--inclusive");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let raw = should_output_raw(args);

    // Get debug level from args
    let debug_level = debug::get_debug_level(args);

    // Log debug information if --debug or --trace flag is present
    let token_store_backend = if std::env::var("SLACK_TOKEN").is_ok() {
        "environment"
    } else {
        "file"
    };

    // Resolve actual token type for debug output
    let resolved_token_type = if let Some(explicit) = token_type {
        explicit
    } else {
        let config_path = default_config_path().map_err(|e| e.to_string())?;
        let profile = resolve_profile_full(&config_path, &profile_name)
            .map_err(|e| format!("Failed to resolve profile '{}': {}", profile_name, e))?;

        if let Some(default_type) = profile.default_token_type {
            default_type
        } else {
            let token_store = create_token_store().map_err(|e| e.to_string())?;
            let user_token_key = format!("{}:{}:user", profile.team_id, profile.user_id);
            if token_store.get(&user_token_key).is_ok() {
                TokenType::User
            } else {
                TokenType::Bot
            }
        }
    };

    let endpoint = "https://slack.com/api/conversations.replies";

    debug::log_api_context(
        debug_level,
        Some(&profile_name),
        token_store_backend,
        resolved_token_type.as_str(),
        "conversations.replies",
        endpoint,
    );

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;
    let inclusive_opt = if inclusive { Some(true) } else { None };
    let response = commands::thread_get(&client, channel, thread_ts, limit, inclusive_opt)
        .await
        .map_err(|e| e.to_string())?;

    // Log error code if present
    debug::log_error_code(
        debug_level,
        &serde_json::to_value(&response).unwrap_or_default(),
    );

    // Display error guidance if response contains a known error
    crate::api::display_wrapper_error_guidance(&response);

    // Output with or without envelope
    let output = if raw {
        serde_json::to_string_pretty(&response).unwrap()
    } else {
        let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
        let wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "conversations.replies",
            "thread get",
            Some(profile_name),
            token_type,
        )
        .await?;
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_users_info(args: &[String]) -> Result<(), String> {
    let user = args[3].clone();
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let raw = should_output_raw(args);

    // Get debug level from args
    let debug_level = debug::get_debug_level(args);

    // Log debug information if --debug or --trace flag is present
    let token_store_backend = if std::env::var("SLACK_TOKEN").is_ok() {
        "environment"
    } else {
        "file"
    };

    // Resolve actual token type for debug output
    let resolved_token_type = if let Some(explicit) = token_type {
        explicit
    } else {
        let config_path = default_config_path().map_err(|e| e.to_string())?;
        let profile = resolve_profile_full(&config_path, &profile_name)
            .map_err(|e| format!("Failed to resolve profile '{}': {}", profile_name, e))?;

        if let Some(default_type) = profile.default_token_type {
            default_type
        } else {
            let token_store = create_token_store().map_err(|e| e.to_string())?;
            let user_token_key = format!("{}:{}:user", profile.team_id, profile.user_id);
            if token_store.get(&user_token_key).is_ok() {
                TokenType::User
            } else {
                TokenType::Bot
            }
        }
    };

    let endpoint = "https://slack.com/api/users.info";

    debug::log_api_context(
        debug_level,
        Some(&profile_name),
        token_store_backend,
        resolved_token_type.as_str(),
        "users.info",
        endpoint,
    );

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;
    let response = commands::users_info(&client, user)
        .await
        .map_err(|e| e.to_string())?;

    // Log error code if present
    debug::log_error_code(
        debug_level,
        &serde_json::to_value(&response).unwrap_or_default(),
    );

    // Display error guidance if response contains a known error
    crate::api::display_wrapper_error_guidance(&response);

    // Output with or without envelope
    let output = if raw {
        serde_json::to_string_pretty(&response).unwrap()
    } else {
        let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
        let wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "users.info",
            "users info",
            Some(profile_name),
            token_type,
        )
        .await?;
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_users_cache_update(args: &[String]) -> Result<(), String> {
    let profile_name = resolve_profile_name(args);
    let force = has_flag(args, "--force");
    let token_type = parse_token_type(args)?;

    let config_path = default_config_path().map_err(|e| e.to_string())?;
    let config = load_config(&config_path).map_err(|e| e.to_string())?;

    let profile = config
        .get(&profile_name)
        .ok_or_else(|| format!("Profile '{}' not found", profile_name))?;

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;

    commands::update_cache(&client, profile.team_id.clone(), force)
        .await
        .map_err(|e| e.to_string())?;

    println!("Cache updated successfully for team {}", profile.team_id);
    Ok(())
}

pub async fn run_users_resolve_mentions(args: &[String]) -> Result<(), String> {
    if args.len() < 4 {
        return Err(
            "Usage: users resolve-mentions <text> [--profile=NAME] [--format=FORMAT]".to_string(),
        );
    }

    let text = args[3].clone();
    let profile_name = resolve_profile_name(args);
    let format_str = get_option(args, "--format=").unwrap_or_else(|| "display_name".to_string());

    let format = format_str.parse::<commands::MentionFormat>().map_err(|_| {
        format!(
            "Invalid format: {}. Use display_name, real_name, or username",
            format_str
        )
    })?;

    let config_path = default_config_path().map_err(|e| e.to_string())?;
    let config = load_config(&config_path).map_err(|e| e.to_string())?;

    let profile = config
        .get(&profile_name)
        .ok_or_else(|| format!("Profile '{}' not found", profile_name))?;

    let cache_path = commands::UsersCacheFile::default_path()?;
    let cache_file = commands::UsersCacheFile::load(&cache_path)?;

    let workspace_cache = cache_file.get_workspace(&profile.team_id).ok_or_else(|| {
        format!(
            "No cache found for team {}. Run 'users cache-update' first.",
            profile.team_id
        )
    })?;

    let result = commands::resolve_mentions(&text, workspace_cache, format);
    println!("{}", result);
    Ok(())
}

/// Get team_id and user_id from profile
async fn get_team_and_user_ids_from_profile(
    profile_name: &str,
) -> Result<(String, String), String> {
    let config_path = default_config_path().map_err(|e| e.to_string())?;
    let profile = resolve_profile_full(&config_path, profile_name)
        .map_err(|e| format!("Failed to resolve profile '{}': {}", profile_name, e))?;
    Ok((profile.team_id, profile.user_id))
}

pub async fn run_msg_post(args: &[String], non_interactive: bool) -> Result<(), String> {
    use crate::idempotency::{IdempotencyCheckResult, IdempotencyHandler};

    if args.len() < 5 {
        return Err("Usage: msg post <channel> <text> [--thread-ts=TS] [--reply-broadcast] [--yes] [--profile=NAME] [--token-type=bot|user] [--idempotency-key=KEY]".to_string());
    }

    let channel = args[3].clone();
    let text = args[4].clone();
    let thread_ts = get_option(args, "--thread-ts=");
    let reply_broadcast = has_flag(args, "--reply-broadcast");
    let yes = has_flag(args, "--yes");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let idempotency_key = get_option(args, "--idempotency-key=");

    // Validate: --reply-broadcast requires --thread-ts
    if reply_broadcast && thread_ts.is_none() {
        return Err("Error: --reply-broadcast requires --thread-ts".to_string());
    }

    let raw = should_output_raw(args);
    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;

    // Check idempotency if key provided
    let (response_value, idempotency_status) = if let Some(key) = idempotency_key.clone() {
        let mut handler = IdempotencyHandler::new().map_err(|e| e.to_string())?;

        // Build params for fingerprinting
        let mut params = serde_json::Map::new();
        params.insert("channel".to_string(), serde_json::json!(channel.clone()));
        params.insert("text".to_string(), serde_json::json!(text.clone()));
        if let Some(ref ts) = thread_ts {
            params.insert("thread_ts".to_string(), serde_json::json!(ts));
            if reply_broadcast {
                params.insert("reply_broadcast".to_string(), serde_json::json!(true));
            }
        }

        // Get team_id and user_id from profile
        let (team_id, user_id) = get_team_and_user_ids_from_profile(&profile_name).await?;

        match handler
            .check(
                Some(key.clone()),
                team_id.clone(),
                user_id.clone(),
                "chat.postMessage".to_string(),
                &params,
            )
            .map_err(|e| e.to_string())?
        {
            IdempotencyCheckResult::Replay {
                response, status, ..
            } => {
                // Return cached response
                (response, Some(status))
            }
            IdempotencyCheckResult::Execute {
                key: scoped_key,
                fingerprint,
            } => {
                // Execute and store
                let response = commands::msg_post(
                    &client,
                    channel,
                    text,
                    thread_ts,
                    reply_broadcast,
                    yes,
                    non_interactive,
                )
                .await
                .map_err(|e| e.to_string())?;

                let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;

                // Store result
                handler
                    .store(scoped_key, fingerprint, response_value.clone())
                    .map_err(|e| e.to_string())?;

                (
                    response_value,
                    Some(crate::idempotency::IdempotencyStatus::Executed),
                )
            }
            IdempotencyCheckResult::NoKey => unreachable!(),
        }
    } else {
        // No idempotency key - execute normally
        let response = commands::msg_post(
            &client,
            channel,
            text,
            thread_ts,
            reply_broadcast,
            yes,
            non_interactive,
        )
        .await
        .map_err(|e| e.to_string())?;

        (
            serde_json::to_value(&response).map_err(|e| e.to_string())?,
            None,
        )
    };

    // Display error guidance if response contains a known error
    if let Ok(api_response) =
        serde_json::from_value::<crate::api::ApiResponse>(response_value.clone())
    {
        crate::api::display_wrapper_error_guidance(&api_response);
    }

    // Output with or without envelope
    let output = if raw {
        serde_json::to_string_pretty(&response_value).unwrap()
    } else {
        let mut wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "chat.postMessage",
            "msg post",
            Some(profile_name),
            token_type,
        )
        .await?;

        // Add idempotency metadata if key was provided
        if let (Some(key), Some(status)) = (idempotency_key, idempotency_status) {
            wrapped = wrapped.with_idempotency(
                key,
                match status {
                    crate::idempotency::IdempotencyStatus::Executed => "executed".to_string(),
                    crate::idempotency::IdempotencyStatus::Replayed => "replayed".to_string(),
                },
            );
        }

        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_msg_update(args: &[String], non_interactive: bool) -> Result<(), String> {
    use crate::idempotency::{IdempotencyCheckResult, IdempotencyHandler};

    if args.len() < 6 {
        return Err("Usage: msg update <channel> <ts> <text> [--yes] [--profile=NAME] [--token-type=bot|user] [--idempotency-key=KEY]".to_string());
    }

    let channel = args[3].clone();
    let ts = args[4].clone();
    let text = args[5].clone();
    let yes = has_flag(args, "--yes");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let idempotency_key = get_option(args, "--idempotency-key=");
    let raw = should_output_raw(args);

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;

    // Check idempotency if key provided
    let (response_value, idempotency_status) = if let Some(key) = idempotency_key.clone() {
        let mut handler = IdempotencyHandler::new().map_err(|e| e.to_string())?;

        let mut params = serde_json::Map::new();
        params.insert("channel".to_string(), serde_json::json!(channel.clone()));
        params.insert("ts".to_string(), serde_json::json!(ts.clone()));
        params.insert("text".to_string(), serde_json::json!(text.clone()));

        let (team_id, user_id) = get_team_and_user_ids_from_profile(&profile_name).await?;

        match handler
            .check(
                Some(key.clone()),
                team_id,
                user_id,
                "chat.update".to_string(),
                &params,
            )
            .map_err(|e| e.to_string())?
        {
            IdempotencyCheckResult::Replay {
                response, status, ..
            } => (response, Some(status)),
            IdempotencyCheckResult::Execute {
                key: scoped_key,
                fingerprint,
            } => {
                let response =
                    commands::msg_update(&client, channel, ts, text, yes, non_interactive)
                        .await
                        .map_err(|e| e.to_string())?;
                let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
                handler
                    .store(scoped_key, fingerprint, response_value.clone())
                    .map_err(|e| e.to_string())?;
                (
                    response_value,
                    Some(crate::idempotency::IdempotencyStatus::Executed),
                )
            }
            IdempotencyCheckResult::NoKey => unreachable!(),
        }
    } else {
        let response = commands::msg_update(&client, channel, ts, text, yes, non_interactive)
            .await
            .map_err(|e| e.to_string())?;
        (
            serde_json::to_value(&response).map_err(|e| e.to_string())?,
            None,
        )
    };

    if let Ok(api_response) =
        serde_json::from_value::<crate::api::ApiResponse>(response_value.clone())
    {
        crate::api::display_wrapper_error_guidance(&api_response);
    }

    let output = if raw {
        serde_json::to_string_pretty(&response_value).unwrap()
    } else {
        let mut wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "chat.update",
            "msg update",
            Some(profile_name),
            token_type,
        )
        .await?;

        if let (Some(key), Some(status)) = (idempotency_key, idempotency_status) {
            wrapped = wrapped.with_idempotency(
                key,
                match status {
                    crate::idempotency::IdempotencyStatus::Executed => "executed".to_string(),
                    crate::idempotency::IdempotencyStatus::Replayed => "replayed".to_string(),
                },
            );
        }

        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_msg_delete(args: &[String], non_interactive: bool) -> Result<(), String> {
    use crate::idempotency::{IdempotencyCheckResult, IdempotencyHandler};

    if args.len() < 5 {
        return Err(
            "Usage: msg delete <channel> <ts> [--yes] [--profile=NAME] [--token-type=bot|user] [--idempotency-key=KEY]"
                .to_string(),
        );
    }

    let channel = args[3].clone();
    let ts = args[4].clone();
    let yes = has_flag(args, "--yes");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let idempotency_key = get_option(args, "--idempotency-key=");
    let raw = should_output_raw(args);

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;

    let (response_value, idempotency_status) = if let Some(key) = idempotency_key.clone() {
        let mut handler = IdempotencyHandler::new().map_err(|e| e.to_string())?;
        let mut params = serde_json::Map::new();
        params.insert("channel".to_string(), serde_json::json!(channel.clone()));
        params.insert("ts".to_string(), serde_json::json!(ts.clone()));
        let (team_id, user_id) = get_team_and_user_ids_from_profile(&profile_name).await?;
        match handler
            .check(
                Some(key.clone()),
                team_id,
                user_id,
                "chat.delete".to_string(),
                &params,
            )
            .map_err(|e| e.to_string())?
        {
            IdempotencyCheckResult::Replay {
                response, status, ..
            } => (response, Some(status)),
            IdempotencyCheckResult::Execute {
                key: scoped_key,
                fingerprint,
            } => {
                let response = commands::msg_delete(&client, channel, ts, yes, non_interactive)
                    .await
                    .map_err(|e| e.to_string())?;
                let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
                handler
                    .store(scoped_key, fingerprint, response_value.clone())
                    .map_err(|e| e.to_string())?;
                (
                    response_value,
                    Some(crate::idempotency::IdempotencyStatus::Executed),
                )
            }
            IdempotencyCheckResult::NoKey => unreachable!(),
        }
    } else {
        let response = commands::msg_delete(&client, channel, ts, yes, non_interactive)
            .await
            .map_err(|e| e.to_string())?;
        (
            serde_json::to_value(&response).map_err(|e| e.to_string())?,
            None,
        )
    };

    if let Ok(api_response) =
        serde_json::from_value::<crate::api::ApiResponse>(response_value.clone())
    {
        crate::api::display_wrapper_error_guidance(&api_response);
    }

    let output = if raw {
        serde_json::to_string_pretty(&response_value).unwrap()
    } else {
        let mut wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "chat.delete",
            "msg delete",
            Some(profile_name),
            token_type,
        )
        .await?;
        if let (Some(key), Some(status)) = (idempotency_key, idempotency_status) {
            wrapped = wrapped.with_idempotency(
                key,
                match status {
                    crate::idempotency::IdempotencyStatus::Executed => "executed".to_string(),
                    crate::idempotency::IdempotencyStatus::Replayed => "replayed".to_string(),
                },
            );
        }
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_react_add(args: &[String], non_interactive: bool) -> Result<(), String> {
    use crate::idempotency::{IdempotencyCheckResult, IdempotencyHandler};

    if args.len() < 6 {
        return Err(
            "Usage: react add <channel> <ts> <emoji> [--yes] [--profile=NAME] [--token-type=bot|user] [--idempotency-key=KEY]"
                .to_string(),
        );
    }

    let channel = args[3].clone();
    let ts = args[4].clone();
    let emoji = args[5].clone();
    let yes = has_flag(args, "--yes");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let idempotency_key = get_option(args, "--idempotency-key=");
    let raw = should_output_raw(args);

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;

    let (response_value, idempotency_status) = if let Some(key) = idempotency_key.clone() {
        let mut handler = IdempotencyHandler::new().map_err(|e| e.to_string())?;
        let mut params = serde_json::Map::new();
        params.insert("channel".to_string(), serde_json::json!(channel.clone()));
        params.insert("timestamp".to_string(), serde_json::json!(ts.clone()));
        params.insert("name".to_string(), serde_json::json!(emoji.clone()));
        let (team_id, user_id) = get_team_and_user_ids_from_profile(&profile_name).await?;
        match handler
            .check(
                Some(key.clone()),
                team_id,
                user_id,
                "reactions.add".to_string(),
                &params,
            )
            .map_err(|e| e.to_string())?
        {
            IdempotencyCheckResult::Replay {
                response, status, ..
            } => (response, Some(status)),
            IdempotencyCheckResult::Execute {
                key: scoped_key,
                fingerprint,
            } => {
                let response =
                    commands::react_add(&client, channel, ts, emoji, yes, non_interactive)
                        .await
                        .map_err(|e| e.to_string())?;
                let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
                handler
                    .store(scoped_key, fingerprint, response_value.clone())
                    .map_err(|e| e.to_string())?;
                (
                    response_value,
                    Some(crate::idempotency::IdempotencyStatus::Executed),
                )
            }
            IdempotencyCheckResult::NoKey => unreachable!(),
        }
    } else {
        let response = commands::react_add(&client, channel, ts, emoji, yes, non_interactive)
            .await
            .map_err(|e| e.to_string())?;
        (
            serde_json::to_value(&response).map_err(|e| e.to_string())?,
            None,
        )
    };

    if let Ok(api_response) =
        serde_json::from_value::<crate::api::ApiResponse>(response_value.clone())
    {
        crate::api::display_wrapper_error_guidance(&api_response);
    }

    let output = if raw {
        serde_json::to_string_pretty(&response_value).unwrap()
    } else {
        let mut wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "reactions.add",
            "react add",
            Some(profile_name),
            token_type,
        )
        .await?;
        if let (Some(key), Some(status)) = (idempotency_key, idempotency_status) {
            wrapped = wrapped.with_idempotency(
                key,
                match status {
                    crate::idempotency::IdempotencyStatus::Executed => "executed".to_string(),
                    crate::idempotency::IdempotencyStatus::Replayed => "replayed".to_string(),
                },
            );
        }
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_react_remove(args: &[String], non_interactive: bool) -> Result<(), String> {
    use crate::idempotency::{IdempotencyCheckResult, IdempotencyHandler};

    if args.len() < 6 {
        return Err(
            "Usage: react remove <channel> <ts> <emoji> [--yes] [--profile=NAME] [--token-type=bot|user] [--idempotency-key=KEY]".to_string(),
        );
    }

    let channel = args[3].clone();
    let ts = args[4].clone();
    let emoji = args[5].clone();
    let yes = has_flag(args, "--yes");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let idempotency_key = get_option(args, "--idempotency-key=");
    let raw = should_output_raw(args);

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;

    let (response_value, idempotency_status) = if let Some(key) = idempotency_key.clone() {
        let mut handler = IdempotencyHandler::new().map_err(|e| e.to_string())?;
        let mut params = serde_json::Map::new();
        params.insert("channel".to_string(), serde_json::json!(channel.clone()));
        params.insert("timestamp".to_string(), serde_json::json!(ts.clone()));
        params.insert("name".to_string(), serde_json::json!(emoji.clone()));
        let (team_id, user_id) = get_team_and_user_ids_from_profile(&profile_name).await?;
        match handler
            .check(
                Some(key.clone()),
                team_id,
                user_id,
                "reactions.remove".to_string(),
                &params,
            )
            .map_err(|e| e.to_string())?
        {
            IdempotencyCheckResult::Replay {
                response, status, ..
            } => (response, Some(status)),
            IdempotencyCheckResult::Execute {
                key: scoped_key,
                fingerprint,
            } => {
                let response =
                    commands::react_remove(&client, channel, ts, emoji, yes, non_interactive)
                        .await
                        .map_err(|e| e.to_string())?;
                let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
                handler
                    .store(scoped_key, fingerprint, response_value.clone())
                    .map_err(|e| e.to_string())?;
                (
                    response_value,
                    Some(crate::idempotency::IdempotencyStatus::Executed),
                )
            }
            IdempotencyCheckResult::NoKey => unreachable!(),
        }
    } else {
        let response = commands::react_remove(&client, channel, ts, emoji, yes, non_interactive)
            .await
            .map_err(|e| e.to_string())?;
        (
            serde_json::to_value(&response).map_err(|e| e.to_string())?,
            None,
        )
    };

    if let Ok(api_response) =
        serde_json::from_value::<crate::api::ApiResponse>(response_value.clone())
    {
        crate::api::display_wrapper_error_guidance(&api_response);
    }

    let output = if raw {
        serde_json::to_string_pretty(&response_value).unwrap()
    } else {
        let mut wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "reactions.remove",
            "react remove",
            Some(profile_name),
            token_type,
        )
        .await?;
        if let (Some(key), Some(status)) = (idempotency_key, idempotency_status) {
            wrapped = wrapped.with_idempotency(
                key,
                match status {
                    crate::idempotency::IdempotencyStatus::Executed => "executed".to_string(),
                    crate::idempotency::IdempotencyStatus::Replayed => "replayed".to_string(),
                },
            );
        }
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_file_upload(args: &[String], non_interactive: bool) -> Result<(), String> {
    use crate::idempotency::{IdempotencyCheckResult, IdempotencyHandler};

    if args.len() < 4 {
        return Err(
            "Usage: file upload <path> [--channel=ID] [--channels=IDs] [--title=TITLE] [--comment=TEXT] [--yes] [--profile=NAME] [--token-type=bot|user] [--idempotency-key=KEY]"
                .to_string(),
        );
    }

    let file_path = args[3].clone();
    let channels = get_option(args, "--channel=").or_else(|| get_option(args, "--channels="));
    let title = get_option(args, "--title=");
    let comment = get_option(args, "--comment=");
    let yes = has_flag(args, "--yes");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let idempotency_key = get_option(args, "--idempotency-key=");
    let raw = should_output_raw(args);

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;

    let (response_value, idempotency_status) = if let Some(key) = idempotency_key.clone() {
        let mut handler = IdempotencyHandler::new().map_err(|e| e.to_string())?;
        let mut params = serde_json::Map::new();
        params.insert("filename".to_string(), serde_json::json!(file_path.clone()));
        if let Some(ref ch) = channels {
            params.insert("channels".to_string(), serde_json::json!(ch));
        }
        if let Some(ref t) = title {
            params.insert("title".to_string(), serde_json::json!(t));
        }
        if let Some(ref c) = comment {
            params.insert("comment".to_string(), serde_json::json!(c));
        }
        let (team_id, user_id) = get_team_and_user_ids_from_profile(&profile_name).await?;
        match handler
            .check(
                Some(key.clone()),
                team_id,
                user_id,
                "files.upload".to_string(),
                &params,
            )
            .map_err(|e| e.to_string())?
        {
            IdempotencyCheckResult::Replay {
                response, status, ..
            } => (response, Some(status)),
            IdempotencyCheckResult::Execute {
                key: scoped_key,
                fingerprint,
            } => {
                let response = commands::file_upload(
                    &client,
                    file_path,
                    channels,
                    title,
                    comment,
                    yes,
                    non_interactive,
                )
                .await
                .map_err(|e| e.to_string())?;
                let response_value = serde_json::to_value(&response).map_err(|e| e.to_string())?;
                handler
                    .store(scoped_key, fingerprint, response_value.clone())
                    .map_err(|e| e.to_string())?;
                (
                    response_value,
                    Some(crate::idempotency::IdempotencyStatus::Executed),
                )
            }
            IdempotencyCheckResult::NoKey => unreachable!(),
        }
    } else {
        let response = commands::file_upload(
            &client,
            file_path,
            channels,
            title,
            comment,
            yes,
            non_interactive,
        )
        .await
        .map_err(|e| e.to_string())?;
        (
            serde_json::to_value(&response).map_err(|e| e.to_string())?,
            None,
        )
    };

    crate::api::display_json_error_guidance(&response_value);

    let output = if raw {
        serde_json::to_string_pretty(&response_value).unwrap()
    } else {
        let mut wrapped = wrap_with_envelope_and_token_type(
            response_value,
            "files.upload",
            "file upload",
            Some(profile_name),
            token_type,
        )
        .await?;
        if let (Some(key), Some(status)) = (idempotency_key, idempotency_status) {
            wrapped = wrapped.with_idempotency(
                key,
                match status {
                    crate::idempotency::IdempotencyStatus::Executed => "executed".to_string(),
                    crate::idempotency::IdempotencyStatus::Replayed => "replayed".to_string(),
                },
            );
        }
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub async fn run_file_download(args: &[String]) -> Result<(), String> {
    if args.len() < 3 {
        return Err(
            "Usage: file download [<file_id>] [--url=URL] [--out=PATH] [--profile=NAME] [--token-type=bot|user]"
                .to_string(),
        );
    }

    // Parse arguments
    let file_id = args.get(3).filter(|arg| !arg.starts_with("--")).cloned();
    let url = get_option(args, "--url=");
    let out = get_option(args, "--out=");
    let profile_name = resolve_profile_name(args);
    let token_type = parse_token_type(args)?;
    let raw = should_output_raw(args);

    // Validate: at least one of file_id or url must be provided
    if file_id.is_none() && url.is_none() {
        return Err("Either <file_id> or --url must be provided".to_string());
    }

    let client = get_api_client_with_token_type(Some(profile_name.clone()), token_type).await?;
    let response = commands::file_download(&client, file_id, url, out)
        .await
        .map_err(|e| e.to_string())?;

    // For --out -, don't print any output (file bytes already written to stdout)
    if let Some(out_path) = response.get("output").and_then(|v| v.as_str()) {
        if out_path == "-" {
            return Ok(());
        }
    }

    // Display error guidance if response contains a known error
    crate::api::display_json_error_guidance(&response);

    // Output with or without envelope
    let output = if raw {
        serde_json::to_string_pretty(&response).unwrap()
    } else {
        let wrapped = wrap_with_envelope_and_token_type(
            response,
            "files.info + download",
            "file download",
            Some(profile_name),
            token_type,
        )
        .await?;
        serde_json::to_string_pretty(&wrapped).unwrap()
    };

    println!("{}", output);
    Ok(())
}

pub fn print_conv_usage(prog: &str) {
    println!("Conv command usage:");
    println!(
        "  {} conv list [--types=TYPE] [--include-private] [--all] [--limit=N] [--filter=KEY:VALUE]... [--format=FORMAT] [--sort=KEY] [--sort-dir=DIR] [--raw] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    List conversations with optional filtering and sorting");
    println!("    Options accept both --option=value and --option value formats");
    println!("    Default: Includes public and private channels (limit=1000, auto-paginated)");
    println!("    Type shortcuts (mutually exclusive with --types):");
    println!("      - --include-private: Include private channels (same as default now)");
    println!(
        "      - --all: Include all conversation types (public_channel,private_channel,im,mpim)"
    );
    println!("    Filters: name:<glob>, is_member:true|false, is_private:true|false");
    println!("      - name:<glob>: Filter by channel name (supports * and ? wildcards)");
    println!("      - is_member:true|false: Filter by membership status");
    println!("      - is_private:true|false: Filter by channel privacy");
    println!("    Formats: json (default), jsonl, table, tsv");
    println!("      - json: JSON format with envelope (use --raw for raw Slack API response)");
    println!("      - jsonl: JSON Lines format (one object per line)");
    println!("      - table: Human-readable table format");
    println!("      - tsv: Tab-separated values");
    println!("    Sort keys: name, created, num_members");
    println!("      - name: Sort by channel name");
    println!("      - created: Sort by creation timestamp");
    println!("      - num_members: Sort by member count");
    println!("    Sort direction: asc (default), desc");
    println!("    Note: --raw is only valid with --format json");
    println!();
    println!(
        "  {} conv search <pattern> [--select] [--types=TYPE] [--limit=N] [--filter=KEY:VALUE]... [--format=FORMAT] [--sort=KEY] [--sort-dir=DIR] [--raw] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    Search conversations by name pattern (applies name:<pattern> filter)");
    println!("    Default: Includes public and private channels (limit=1000, auto-paginated)");
    println!("    Options accept both --option=value and --option value formats");
    println!("    --select: Interactively select from results and output channel ID only");
    println!();
    println!(
        "  {} conv select [--types=TYPE] [--filter=KEY:VALUE]... [--profile=NAME]",
        prog
    );
    println!("    Interactively select a conversation and output its channel ID");
    println!("    Default: Includes public and private channels (limit=1000, auto-paginated)");
    println!("    Options accept both --option=value and --option value formats");
    println!();
    println!(
        "  {} conv history <channel> [--limit=N] [--oldest=TS] [--latest=TS] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!(
        "  {} conv history --interactive [--types=TYPE] [--filter=KEY:VALUE]... [--limit=N] [--profile=NAME]",
        prog
    );
    println!("    Select channel interactively before fetching history");
    println!("    Default: Includes public and private channels (limit=1000, auto-paginated)");
    println!("    Options accept both --option=value and --option value formats");
}

pub fn print_thread_usage(prog: &str) {
    println!("Thread command usage:");
    println!(
        "  {} thread get <channel> <thread_ts> [--limit=N] [--inclusive] [--raw] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    Get thread messages (conversation replies) for a specific thread");
    println!("    Arguments:");
    println!("      <channel>    - Channel ID containing the thread");
    println!("      <thread_ts>  - Timestamp of the parent message (thread identifier)");
    println!("    Options:");
    println!("      --limit=N           - Number of messages per page (default: 100)");
    println!("      --inclusive         - Include the parent message in results");
    println!("      --raw               - Output raw Slack API response without envelope");
    println!("      --profile=NAME      - Profile to use (default: 'default')");
    println!("      --token-type=TYPE   - Token type to use (bot or user)");
    println!("    Note: Automatically follows pagination to retrieve all thread messages");
}

pub fn print_users_usage(prog: &str) {
    println!("Users command usage:");
    println!(
        "  {} users info <user_id> [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!(
        "  {} users cache-update [--profile=NAME] [--force] [--token-type=bot|user]",
        prog
    );
    println!("  {} users resolve-mentions <text> [--profile=NAME] [--format=display_name|real_name|username]", prog);
    println!("  Options accept both --option=value and --option value formats");
}

pub fn print_msg_usage(prog: &str) {
    println!("Msg command usage:");
    println!(
        "  {} msg post <channel> <text> [--thread-ts=TS] [--reply-broadcast] [--idempotency-key=KEY] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    Requires SLACKCLI_ALLOW_WRITE=true environment variable");
    println!(
        "  {} msg update <channel> <ts> <text> [--yes] [--idempotency-key=KEY] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    Requires SLACKCLI_ALLOW_WRITE=true environment variable");
    println!(
        "  {} msg delete <channel> <ts> [--yes] [--idempotency-key=KEY] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    Requires SLACKCLI_ALLOW_WRITE=true environment variable");
    println!("  Options accept both --option=value and --option value formats");
    println!("  --idempotency-key: Prevent duplicate writes (replays stored result on retry)");
}

pub fn print_react_usage(prog: &str) {
    println!("React command usage:");
    println!(
        "  {} react add <channel> <ts> <emoji> [--idempotency-key=KEY] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    Requires SLACKCLI_ALLOW_WRITE=true environment variable");
    println!(
        "  {} react remove <channel> <ts> <emoji> [--yes] [--idempotency-key=KEY] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    Requires SLACKCLI_ALLOW_WRITE=true environment variable");
    println!("  Options accept both --option=value and --option value formats");
    println!("  --idempotency-key: Prevent duplicate writes (replays stored result on retry)");
}

pub fn print_file_usage(prog: &str) {
    println!("File command usage:");
    println!(
        "  {} file upload <path> [--channel=ID] [--channels=IDs] [--title=TITLE] [--comment=TEXT] [--idempotency-key=KEY] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    Upload a file using external upload method");
    println!("    Requires SLACKCLI_ALLOW_WRITE=true environment variable");
    println!(
        "  {} file download [<file_id>] [--url=URL] [--out=PATH] [--profile=NAME] [--token-type=bot|user]",
        prog
    );
    println!("    Download a file from Slack");
    println!("    Either <file_id> or --url must be provided");
    println!("    --out: Output path (omit for current directory, '-' for stdout, directory for auto-naming)");
    println!("  Options accept both --option=value and --option value formats");
    println!("  --idempotency-key: Prevent duplicate writes (replays stored result on retry, upload only)");
}

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

    #[test]
    fn test_parse_token_type_equals_format() {
        let args = vec!["command".to_string(), "--token-type=user".to_string()];
        let result = parse_token_type(&args).unwrap();
        assert_eq!(result, Some(TokenType::User));
    }

    #[test]
    fn test_parse_token_type_space_separated() {
        let args = vec![
            "command".to_string(),
            "--token-type".to_string(),
            "bot".to_string(),
        ];
        let result = parse_token_type(&args).unwrap();
        assert_eq!(result, Some(TokenType::Bot));
    }

    #[test]
    fn test_parse_token_type_both_values() {
        // Test user with equals
        let args1 = vec!["--token-type=user".to_string()];
        assert_eq!(parse_token_type(&args1).unwrap(), Some(TokenType::User));

        // Test bot with equals
        let args2 = vec!["--token-type=bot".to_string()];
        assert_eq!(parse_token_type(&args2).unwrap(), Some(TokenType::Bot));

        // Test user with space
        let args3 = vec!["--token-type".to_string(), "user".to_string()];
        assert_eq!(parse_token_type(&args3).unwrap(), Some(TokenType::User));

        // Test bot with space
        let args4 = vec!["--token-type".to_string(), "bot".to_string()];
        assert_eq!(parse_token_type(&args4).unwrap(), Some(TokenType::Bot));
    }

    #[test]
    fn test_parse_token_type_missing() {
        let args = vec!["command".to_string()];
        let result = parse_token_type(&args).unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_token_type_missing_value() {
        let args = vec!["--token-type".to_string()];
        let result = parse_token_type(&args);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            "--token-type requires a value (bot or user)"
        );
    }

    #[test]
    fn test_parse_token_type_invalid_value() {
        let args = vec!["--token-type=invalid".to_string()];
        let result = parse_token_type(&args);
        assert!(result.is_err());
    }

    // Mock token store for testing
    struct MockTokenStore {
        tokens: std::collections::HashMap<String, String>,
    }

    impl MockTokenStore {
        fn new() -> Self {
            Self {
                tokens: std::collections::HashMap::new(),
            }
        }

        fn with_token(mut self, key: &str, value: &str) -> Self {
            self.tokens.insert(key.to_string(), value.to_string());
            self
        }
    }

    impl TokenStore for MockTokenStore {
        fn get(&self, key: &str) -> crate::profile::token_store::Result<String> {
            use crate::profile::token_store::TokenStoreError;
            self.tokens
                .get(key)
                .cloned()
                .ok_or_else(|| TokenStoreError::NotFound(key.to_string()))
        }

        fn set(&self, _key: &str, _value: &str) -> crate::profile::token_store::Result<()> {
            unimplemented!("set not needed for tests")
        }

        fn delete(&self, _key: &str) -> crate::profile::token_store::Result<()> {
            unimplemented!("delete not needed for tests")
        }

        fn exists(&self, key: &str) -> bool {
            self.tokens.contains_key(key)
        }
    }

    #[test]
    fn test_resolve_token_prefers_env() {
        // SLACK_TOKEN should be preferred over token store
        let store = MockTokenStore::new().with_token("T123:U123", "xoxb-store-token");

        let result = resolve_token_for_wrapper(
            Some("xoxb-env-token".to_string()),
            &store,
            "T123:U123",
            None,
            false,
        );

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "xoxb-env-token");
    }

    #[test]
    fn test_resolve_token_uses_store() {
        // When SLACK_TOKEN is not set, use token store
        let store = MockTokenStore::new().with_token("T123:U123", "xoxb-store-token");

        let result = resolve_token_for_wrapper(None, &store, "T123:U123", None, false);

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "xoxb-store-token");
    }

    #[test]
    fn test_resolve_token_explicit_request() {
        // When token type is explicitly requested, don't fallback
        let store = MockTokenStore::new().with_token("T123:U123", "xoxb-bot-token");

        let result = resolve_token_for_wrapper(
            None,
            &store,
            "T123:U123:user",  // User token key
            Some("T123:U123"), // Bot token fallback
            true,              // Explicit request
        );

        assert!(result.is_err());
        assert!(result.unwrap_err().contains("explicitly requested"));
    }

    #[test]
    fn test_resolve_token_fallback_when_not_explicit() {
        // When token type is not explicitly requested, allow fallback
        let store = MockTokenStore::new().with_token("T123:U123", "xoxb-bot-token");

        let result = resolve_token_for_wrapper(
            None,
            &store,
            "T123:U123:user",  // User token key (not found)
            Some("T123:U123"), // Bot token fallback
            false,             // Not explicit request
        );

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "xoxb-bot-token");
    }

    #[test]
    fn test_resolve_token_env_overrides_explicit() {
        // SLACK_TOKEN should override even explicit token type requests
        let store = MockTokenStore::new()
            .with_token("T123:U123", "xoxb-bot-token")
            .with_token("T123:U123:user", "xoxp-user-token");

        let result = resolve_token_for_wrapper(
            Some("xoxb-env-token".to_string()),
            &store,
            "T123:U123:user",
            None,
            true, // Explicit request
        );

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "xoxb-env-token");
    }

    // Tests for get_option with space-separated format
    #[test]
    fn test_get_option_equals_format() {
        let args = vec!["cmd".to_string(), "--filter=is_private:true".to_string()];
        assert_eq!(
            get_option(&args, "--filter="),
            Some("is_private:true".to_string())
        );
    }

    #[test]
    fn test_get_option_space_separated() {
        let args = vec![
            "cmd".to_string(),
            "--filter".to_string(),
            "is_private:true".to_string(),
        ];
        assert_eq!(
            get_option(&args, "--filter="),
            Some("is_private:true".to_string())
        );
    }

    #[test]
    fn test_get_option_space_separated_rejects_dash_value() {
        // Value starting with '-' should not be treated as value
        let args = vec![
            "cmd".to_string(),
            "--filter".to_string(),
            "--other".to_string(),
        ];
        assert_eq!(get_option(&args, "--filter="), None);
    }

    #[test]
    fn test_get_option_space_separated_missing_value() {
        let args = vec!["cmd".to_string(), "--filter".to_string()];
        assert_eq!(get_option(&args, "--filter="), None);
    }

    #[test]
    fn test_get_option_prefers_equals_format() {
        // When both formats exist, equals format should be returned first
        let args = vec![
            "--filter=value1".to_string(),
            "--filter".to_string(),
            "value2".to_string(),
        ];
        assert_eq!(get_option(&args, "--filter="), Some("value1".to_string()));
    }

    // Tests for get_all_options with mixed formats
    #[test]
    fn test_get_all_options_equals_format() {
        let args = vec![
            "cmd".to_string(),
            "--filter=is_private:true".to_string(),
            "--filter=is_member:true".to_string(),
        ];
        let result = get_all_options(&args, "--filter=");
        assert_eq!(result, vec!["is_private:true", "is_member:true"]);
    }

    #[test]
    fn test_get_all_options_space_separated() {
        let args = vec![
            "cmd".to_string(),
            "--filter".to_string(),
            "is_private:true".to_string(),
            "--filter".to_string(),
            "is_member:true".to_string(),
        ];
        let result = get_all_options(&args, "--filter=");
        assert_eq!(result, vec!["is_private:true", "is_member:true"]);
    }

    #[test]
    fn test_get_all_options_mixed_format() {
        let args = vec![
            "cmd".to_string(),
            "--filter=is_private:true".to_string(),
            "--filter".to_string(),
            "is_member:true".to_string(),
            "--filter=name:test".to_string(),
            "--filter".to_string(),
            "is_archived:false".to_string(),
        ];
        let result = get_all_options(&args, "--filter=");
        assert_eq!(
            result,
            vec![
                "is_private:true",
                "name:test",
                "is_member:true",
                "is_archived:false"
            ]
        );
    }

    #[test]
    fn test_get_all_options_rejects_dash_values() {
        let args = vec![
            "cmd".to_string(),
            "--filter=value1".to_string(),
            "--filter".to_string(),
            "--other".to_string(), // Should be ignored
            "--filter".to_string(),
            "value2".to_string(),
        ];
        let result = get_all_options(&args, "--filter=");
        assert_eq!(result, vec!["value1", "value2"]);
    }

    #[test]
    fn test_get_all_options_space_separated_at_end() {
        // --filter at the end without value should be ignored
        let args = vec![
            "cmd".to_string(),
            "--filter=value1".to_string(),
            "--filter".to_string(),
        ];
        let result = get_all_options(&args, "--filter=");
        assert_eq!(result, vec!["value1"]);
    }

    // Integration tests for conv commands with space-separated options
    #[test]
    fn test_conv_list_filter_space_separated() {
        // Test that filter parsing works with space-separated format
        let args = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--filter".to_string(),
            "is_private:true".to_string(),
        ];
        let filters = get_all_options(&args, "--filter=");
        assert_eq!(filters.len(), 1);
        assert_eq!(filters[0], "is_private:true");
    }

    #[test]
    fn test_conv_list_multiple_filters_mixed() {
        let args = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--filter=is_private:true".to_string(),
            "--filter".to_string(),
            "is_member:true".to_string(),
        ];
        let filters = get_all_options(&args, "--filter=");
        assert_eq!(filters.len(), 2);
        assert_eq!(filters[0], "is_private:true");
        assert_eq!(filters[1], "is_member:true");
    }

    #[test]
    fn test_conv_search_options_space_separated() {
        let args = vec![
            "slack".to_string(),
            "conv".to_string(),
            "search".to_string(),
            "pattern".to_string(),
            "--format".to_string(),
            "table".to_string(),
            "--sort".to_string(),
            "name".to_string(),
        ];
        assert_eq!(get_option(&args, "--format="), Some("table".to_string()));
        assert_eq!(get_option(&args, "--sort="), Some("name".to_string()));
    }

    #[test]
    fn test_search_command_options_space_separated() {
        let args = vec![
            "slack".to_string(),
            "search".to_string(),
            "query".to_string(),
            "--count".to_string(),
            "10".to_string(),
            "--sort".to_string(),
            "timestamp".to_string(),
        ];
        assert_eq!(get_option(&args, "--count="), Some("10".to_string()));
        assert_eq!(get_option(&args, "--sort="), Some("timestamp".to_string()));
    }

    // Tests for resolve_profile_name function
    #[test]
    fn test_resolve_profile_name_with_equals_format() {
        let args = vec![
            "slack".to_string(),
            "api".to_string(),
            "call".to_string(),
            "--profile=myprofile".to_string(),
            "test.method".to_string(),
        ];
        assert_eq!(resolve_profile_name(&args), "myprofile");
    }

    #[test]
    fn test_resolve_profile_name_with_space_format() {
        let args = vec![
            "slack".to_string(),
            "api".to_string(),
            "call".to_string(),
            "--profile".to_string(),
            "myprofile".to_string(),
            "test.method".to_string(),
        ];
        assert_eq!(resolve_profile_name(&args), "myprofile");
    }

    #[test]
    fn test_resolve_profile_name_at_beginning() {
        let args = vec![
            "slack".to_string(),
            "--profile=myprofile".to_string(),
            "api".to_string(),
            "call".to_string(),
            "test.method".to_string(),
        ];
        assert_eq!(resolve_profile_name(&args), "myprofile");
    }

    #[test]
    fn test_resolve_profile_name_at_end() {
        let args = vec![
            "slack".to_string(),
            "api".to_string(),
            "call".to_string(),
            "test.method".to_string(),
            "--profile=myprofile".to_string(),
        ];
        assert_eq!(resolve_profile_name(&args), "myprofile");
    }

    #[test]
    #[serial_test::serial]
    fn test_resolve_profile_name_env_fallback() {
        // Set environment variable
        std::env::set_var("SLACK_PROFILE", "envprofile");

        let args = vec!["slack".to_string(), "api".to_string(), "call".to_string()];
        assert_eq!(resolve_profile_name(&args), "envprofile");

        // Clean up
        std::env::remove_var("SLACK_PROFILE");
    }

    #[test]
    #[serial_test::serial]
    fn test_resolve_profile_name_default_fallback() {
        // Ensure SLACK_PROFILE is not set
        std::env::remove_var("SLACK_PROFILE");

        let args = vec!["slack".to_string(), "api".to_string(), "call".to_string()];
        assert_eq!(resolve_profile_name(&args), "default");
    }

    #[test]
    #[serial_test::serial]
    fn test_resolve_profile_name_flag_overrides_env() {
        // Set environment variable
        std::env::set_var("SLACK_PROFILE", "envprofile");

        let args = vec![
            "slack".to_string(),
            "api".to_string(),
            "--profile=flagprofile".to_string(),
            "call".to_string(),
        ];
        assert_eq!(resolve_profile_name(&args), "flagprofile");

        // Clean up
        std::env::remove_var("SLACK_PROFILE");
    }

    #[test]
    #[serial_test::serial]
    fn test_resolve_profile_name_priority_all_sources() {
        // Set environment variable
        std::env::set_var("SLACK_PROFILE", "envprofile");

        // Test that --profile flag takes highest priority
        let args = vec![
            "--profile".to_string(),
            "flagprofile".to_string(),
            "slack".to_string(),
            "api".to_string(),
            "call".to_string(),
        ];
        assert_eq!(resolve_profile_name(&args), "flagprofile");

        // Clean up
        std::env::remove_var("SLACK_PROFILE");
    }

    #[test]
    fn test_resolve_profile_name_mixed_formats() {
        // Test that equals format is found even with space format present
        let args = vec![
            "slack".to_string(),
            "--profile=profile1".to_string(),
            "api".to_string(),
            "--profile".to_string(),
            "profile2".to_string(),
            "call".to_string(),
        ];
        // Should return profile1 as equals format is checked first
        assert_eq!(resolve_profile_name(&args), "profile1");
    }

    #[test]
    fn test_conv_list_include_private_flag() {
        let args = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--include-private".to_string(),
        ];
        assert!(has_flag(&args, "--include-private"));
        assert!(!has_flag(&args, "--all"));
    }

    #[test]
    fn test_conv_list_all_flag() {
        let args = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--all".to_string(),
        ];
        assert!(!has_flag(&args, "--include-private"));
        assert!(has_flag(&args, "--all"));
    }

    #[test]
    fn test_conv_list_types_exclude_private_all() {
        // This test verifies the flag detection logic
        // The actual exclusivity check happens in run_conv_list
        let args_with_types = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--types=public_channel".to_string(),
        ];
        assert_eq!(
            get_option(&args_with_types, "--types="),
            Some("public_channel".to_string())
        );

        let args_with_private = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--types=public_channel".to_string(),
            "--include-private".to_string(),
        ];
        assert_eq!(
            get_option(&args_with_private, "--types="),
            Some("public_channel".to_string())
        );
        assert!(has_flag(&args_with_private, "--include-private"));
    }

    #[test]
    fn test_conv_list_types_resolution_logic() {
        // Test types resolution without flags
        let args_no_flags = vec!["slack".to_string(), "conv".to_string(), "list".to_string()];
        let types = get_option(&args_no_flags, "--types=");
        let include_private = has_flag(&args_no_flags, "--include-private");
        let all = has_flag(&args_no_flags, "--all");
        assert!(types.is_none());
        assert!(!include_private);
        assert!(!all);

        // Test with --include-private
        let args_private = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--include-private".to_string(),
        ];
        let types = get_option(&args_private, "--types=");
        let include_private = has_flag(&args_private, "--include-private");
        let all = has_flag(&args_private, "--all");
        assert!(types.is_none());
        assert!(include_private);
        assert!(!all);

        // Test with --all
        let args_all = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--all".to_string(),
        ];
        let types = get_option(&args_all, "--types=");
        let include_private = has_flag(&args_all, "--include-private");
        let all = has_flag(&args_all, "--all");
        assert!(types.is_none());
        assert!(!include_private);
        assert!(all);

        // Test mutual exclusion: --types with --include-private
        let args_conflict1 = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--types=public_channel".to_string(),
            "--include-private".to_string(),
        ];
        let types = get_option(&args_conflict1, "--types=");
        let include_private = has_flag(&args_conflict1, "--include-private");
        assert!(types.is_some());
        assert!(include_private);
        // This should trigger error in run_conv_list

        // Test mutual exclusion: --types with --all
        let args_conflict2 = vec![
            "slack".to_string(),
            "conv".to_string(),
            "list".to_string(),
            "--types=public_channel".to_string(),
            "--all".to_string(),
        ];
        let types = get_option(&args_conflict2, "--types=");
        let all = has_flag(&args_conflict2, "--all");
        assert!(types.is_some());
        assert!(all);
        // This should trigger error in run_conv_list
    }
}