linear-cli 0.3.13

A powerful CLI for Linear.app - manage issues, projects, cycles, and more from your terminal
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
mod api;
mod cache;
mod commands;
mod config;
mod dates;
mod error;
mod input;
mod json_path;
mod oauth;
#[cfg(feature = "secure-storage")]
mod keyring;
mod output;
mod pagination;
mod priority;
mod retry;
mod text;
#[allow(dead_code)]
mod types;
mod vcs;

use anyhow::Result;
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{generate, Shell};
use commands::{
    attachments, auth, bulk, comments, cycles, doctor, documents, export, favorites, git, history,
    import, initiatives, interactive, issues, labels, metrics, notifications, project_updates,
    projects, relations, roadmaps, search, sprint, statuses, sync, teams, templates, time, triage,
    uploads, users, views, watch, webhooks,
};
use error::CliError;
use output::print_json_owned;
use output::{parse_filters, JsonOutputOptions, OutputOptions, SortOrder};
use pagination::PaginationOptions;
use std::io::IsTerminal;
use std::sync::OnceLock;

/// Output format for command results
#[derive(Debug, Clone, Copy, Default, ValueEnum, PartialEq)]
pub enum OutputFormat {
    /// Display results as formatted tables (default)
    #[default]
    Table,
    /// Display results as raw JSON
    Json,
    /// Display results as NDJSON (one JSON object per line)
    Ndjson,
}

#[derive(Debug, Clone, Copy, Default, ValueEnum, PartialEq)]
pub enum ColorChoice {
    #[default]
    Auto,
    Always,
    Never,
}

/// Global options for agentic/scripting use
#[derive(Debug, Clone, Copy, Default)]
pub struct AgentOptions {
    /// Suppress decorative output (headers, separators, tips)
    pub quiet: bool,
    /// Only output IDs of created/updated resources
    pub id_only: bool,
    /// Preview without making changes (where supported)
    pub dry_run: bool,
    /// Auto-confirm all prompts (deletes, destructive operations)
    pub yes: bool,
}

static YES_MODE: OnceLock<bool> = OnceLock::new();

pub fn set_yes_mode(yes: bool) {
    let _ = YES_MODE.set(yes);
}

pub fn is_yes() -> bool {
    YES_MODE.get().copied().unwrap_or(false)
}

#[derive(Parser)]
#[command(name = "linear-cli")]
#[command(
    about = "A powerful CLI for Linear.app - manage issues, projects, and more from your terminal"
)]
#[command(version)]
#[command(after_help = r#"QUICK START:
    1. Get your API key from https://linear.app/settings/api
    2. Configure the CLI:
       linear config set-key YOUR_API_KEY
    3. List your issues:
       linear issues list
    4. Create an issue:
       linear issues create "Fix bug" --team ENG --priority 2

COMMON FLAGS:
    --output table|json|ndjson    Output format (default: table)
    --color-mode auto|always|never   Color output control
    --no-color                    Disable color output
    --width N                     Max table column width
    --no-truncate                 Disable table truncation
    --quiet                       Reduce decorative output
    --format TEMPLATE             Template output (e.g. '{{identifier}} {{title}}')
    --filter field=value          Filter results (=, !=, ~= operators; dot paths; case-insensitive)
    --limit N                     Limit list/search results
    --page-size N                 Page size for list/search
    --after CURSOR                Pagination cursor (after)
    --before CURSOR               Pagination cursor (before)
    --all                         Fetch all pages
    --profile NAME                Use named profile
    --schema                      Print JSON schema version and exit
    --cache-ttl N                 Cache TTL in seconds
    --no-cache                    Disable cache usage
    --yes                         Auto-confirm all prompts

For more info on a command, run: linear <command> --help"#)]
struct Cli {
    /// Output format (table or json)
    #[arg(
        short,
        long,
        global = true,
        env = "LINEAR_CLI_OUTPUT",
        default_value = "table"
    )]
    output: OutputFormat,

    /// Suppress decorative output (headers, separators, tips) - for scripting
    #[arg(short, long, global = true)]
    quiet: bool,

    /// Only output IDs of created/updated resources - for chaining commands
    #[arg(long, global = true)]
    id_only: bool,

    /// Color output: auto, always, or never
    #[arg(
        long = "color-mode",
        global = true,
        value_enum,
        default_value = "auto",
        conflicts_with = "no_color"
    )]
    color_mode: ColorChoice,

    /// Disable color output
    #[arg(long, global = true)]
    no_color: bool,

    /// Max column width for table output (default: 50)
    #[arg(long, global = true)]
    width: Option<usize>,

    /// Disable truncation for table output
    #[arg(long, global = true)]
    no_truncate: bool,

    /// Emit compact JSON without pretty formatting
    #[arg(long, global = true)]
    compact: bool,

    /// Limit JSON output to specific fields (comma-separated, supports dot paths)
    #[arg(long, global = true, value_delimiter = ',')]
    fields: Vec<String>,

    /// Sort JSON array output by a field (default: identifier/id when available)
    #[arg(long, global = true)]
    sort: Option<String>,

    /// Sort order for JSON array output
    #[arg(long, global = true, value_enum, default_value = "asc")]
    order: SortOrder,

    /// Override API key for this invocation
    #[arg(long, global = true, env = "LINEAR_API_KEY")]
    api_key: Option<String>,

    /// Override workspace profile for this invocation
    #[arg(long, global = true, env = "LINEAR_CLI_PROFILE")]
    profile: Option<String>,

    /// Output using a template (e.g. '{{identifier}} {{title}}')
    #[arg(long, global = true)]
    format: Option<String>,

    /// Filter results (field=value, field!=value, field~=value).
    /// Supports dot-notation for nested fields (e.g. state.name=Done).
    /// ~= is a case-insensitive "contains" match. All comparisons are case-insensitive.
    /// Multiple --filter flags are combined with AND logic.
    #[arg(long, global = true)]
    filter: Vec<String>,

    /// Exit with non-zero status when a list is empty
    #[arg(long, global = true)]
    fail_on_empty: bool,

    /// Max results to return for list/search commands
    #[arg(long, global = true)]
    limit: Option<usize>,

    /// Pagination cursor to start after
    #[arg(long, global = true)]
    after: Option<String>,

    /// Pagination cursor to end before
    #[arg(long, global = true)]
    before: Option<String>,

    /// Page size per request for list/search commands
    #[arg(long, global = true)]
    page_size: Option<usize>,

    /// Fetch all pages for list/search commands
    #[arg(long, global = true)]
    all: bool,

    /// Override cache TTL in seconds
    #[arg(long, global = true, env = "LINEAR_CLI_CACHE_TTL")]
    cache_ttl: Option<u64>,

    /// Disable cache usage for this invocation
    #[arg(long, global = true, env = "LINEAR_CLI_NO_CACHE")]
    no_cache: bool,

    /// Preview without making changes where supported
    #[arg(long, global = true)]
    dry_run: bool,

    /// Auto-confirm all prompts (deletes, destructive operations)
    #[arg(long, global = true, env = "LINEAR_CLI_YES")]
    yes: bool,

    /// Number of retries for failed API requests (with exponential backoff)
    #[arg(long, global = true, default_value = "0")]
    retry: u32,

    /// Print JSON schema version info and exit
    #[arg(long, global = true)]
    schema: bool,

    /// Disable pager for output (default: auto-detect from terminal)
    #[arg(long, global = true, env = "LINEAR_CLI_NO_PAGER")]
    no_pager: bool,

    /// Show common tasks and examples
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Clone, Copy, Default)]
pub struct DisplayOptions {
    pub width: Option<usize>,
    pub no_truncate: bool,
}

impl DisplayOptions {
    pub fn max_width(&self, default: usize) -> Option<usize> {
        if self.no_truncate {
            None
        } else {
            Some(self.width.unwrap_or(default))
        }
    }
}

static DISPLAY_OPTIONS: OnceLock<DisplayOptions> = OnceLock::new();

fn set_cli_state(display: DisplayOptions) {
    let _ = DISPLAY_OPTIONS.set(display);
}

pub fn display_options() -> DisplayOptions {
    DISPLAY_OPTIONS.get().copied().unwrap_or_default()
}

#[derive(Subcommand)]
enum Commands {
    /// Show common tasks and examples
    #[command(alias = "tasks")]
    Common,
    /// Show agent-focused capabilities and examples
    Agent,
    /// Manage issue attachments - list, create, update, delete, link URLs
    #[command(alias = "att")]
    #[command(after_help = r#"EXAMPLES:
    linear attachments list SCW-123          # List attachments on issue
    linear att get ATTACHMENT_ID             # View attachment details
    linear att create SCW-123 -T "Doc" -u https://example.com
    linear att link-url SCW-123 https://example.com
    linear att delete ATTACHMENT_ID --force  # Delete attachment"#)]
    Attachments {
        #[command(subcommand)]
        action: attachments::AttachmentCommands,
    },
    /// Authenticate and manage API keys
    #[command(after_help = r#"EXAMPLES:
    linear auth login                        # Store API key
    linear auth status                       # Show auth status
    linear auth logout                       # Remove current profile
    linear auth oauth                        # Authenticate via OAuth 2.0
    linear auth oauth --client-id MY_ID      # Use custom OAuth app
    linear auth revoke                       # Revoke OAuth tokens"#)]
    Auth {
        #[command(subcommand)]
        action: auth::AuthCommands,
    },
    /// Diagnose configuration and connectivity
    #[command(after_help = r#"EXAMPLES:
    linear doctor                            # Check config and auth
    linear doctor --check-api                # Validate API access
    linear doctor --fix                      # Auto-fix common issues"#)]
    Doctor {
        /// Validate API connectivity and auth
        #[arg(long)]
        check_api: bool,
        /// Auto-fix common issues (stale cache, missing config, invalid API key)
        #[arg(long)]
        fix: bool,
    },
    /// Execute raw GraphQL queries and mutations against the Linear API
    #[command(after_help = r#"EXAMPLES:
    linear api query '{ viewer { id name } }'
    linear api query -v teamId=abc '...'     # With variables
    linear api mutate -v title=Bug '...'     # Run mutations"#)]
    Api {
        #[command(subcommand)]
        action: commands::api::ApiCommands,
    },
    /// Manage projects - list, create, update, delete projects
    #[command(alias = "p")]
    #[command(after_help = r#"EXAMPLES:
    linear projects list                    # List all projects
    linear p list --archived                # Include archived projects
    linear p get PROJECT_ID                 # View project details
    linear p create "Q1 Roadmap" -t ENG     # Create a project"#)]
    Projects {
        #[command(subcommand)]
        action: projects::ProjectCommands,
    },
    /// Manage project status updates - list, create, update, archive
    #[command(alias = "pu")]
    #[command(after_help = r#"EXAMPLES:
    linear project-updates list "My Project"   # List updates
    linear pu get UPDATE_ID                    # View update details
    linear pu create "My Project" -b "On track" # Create update
    linear pu archive UPDATE_ID                # Archive update"#)]
    ProjectUpdates {
        #[command(subcommand)]
        action: project_updates::ProjectUpdateCommands,
    },
    /// Manage issues - list, create, update, assign, track issues
    #[command(alias = "i")]
    #[command(after_help = r#"EXAMPLES:
    linear issues list                      # List all issues
    linear i list -t ENG -s "In Progress"   # Filter by team and status
    linear i get LIN-123                    # View issue details
    linear i create "Bug fix" -t ENG -p 2   # Create high priority issue
    linear i update LIN-123 -s Done         # Update issue status"#)]
    Issues {
        #[command(subcommand)]
        action: issues::IssueCommands,
    },
    /// Manage labels - create and organize project/issue labels
    #[command(alias = "l")]
    #[command(after_help = r##"EXAMPLES:
    linear labels list                      # List project labels
    linear l list --type issue              # List issue labels
    linear l create "Feature" --color "#10B981"
    linear l delete LABEL_ID --force"##)]
    Labels {
        #[command(subcommand)]
        action: labels::LabelCommands,
    },
    /// Manage teams - list and view team details
    #[command(alias = "t")]
    #[command(after_help = r#"EXAMPLES:
    linear teams list                       # List all teams
    linear t get ENG                        # View team details"#)]
    Teams {
        #[command(subcommand)]
        action: teams::TeamCommands,
    },
    /// Manage users - list workspace users and view profiles
    #[command(alias = "u")]
    #[command(after_help = r#"EXAMPLES:
    linear users list                       # List all users
    linear u list --team ENG                # List team members
    linear u me                             # View your profile"#)]
    Users {
        #[command(subcommand)]
        action: users::UserCommands,
    },
    /// Manage cycles - view sprint cycles and current cycle
    #[command(alias = "c")]
    #[command(after_help = r#"EXAMPLES:
    linear cycles list -t ENG               # List team cycles
    linear c current -t ENG                 # Show current cycle
    linear c create -t ENG --name "Sprint 5" # Create a cycle
    linear c update ID --name "Sprint 5b"   # Update cycle name"#)]
    Cycles {
        #[command(subcommand)]
        action: cycles::CycleCommands,
    },
    /// Manage comments - add and view issue comments
    #[command(alias = "cm")]
    #[command(after_help = r#"EXAMPLES:
    linear comments list ISSUE_ID           # List comments on issue
    linear cm create ISSUE_ID -b "LGTM!"    # Add a comment"#)]
    Comments {
        #[command(subcommand)]
        action: comments::CommentCommands,
    },
    /// Manage documents - create, update, delete documentation
    #[command(alias = "d")]
    #[command(after_help = r#"EXAMPLES:
    linear documents list                   # List all documents
    linear d get DOC_ID                     # View document
    linear d create "Design Doc" -p PROJ_ID # Create document
    linear d delete DOC_ID --force          # Delete document"#)]
    Documents {
        #[command(subcommand)]
        action: documents::DocumentCommands,
    },
    /// Search across Linear - find issues and projects
    #[command(alias = "s")]
    #[command(after_help = r#"EXAMPLES:
    linear search issues "auth bug"         # Search issues
    linear s projects "backend"             # Search projects"#)]
    Search {
        #[command(subcommand)]
        action: search::SearchCommands,
    },
    /// Sync operations - compare local folders with Linear
    #[command(alias = "sy")]
    #[command(after_help = r#"EXAMPLES:
    linear sync status                      # Compare local vs Linear
    linear sy push -t ENG                   # Create projects for folders
    linear sy push -t ENG --dry-run         # Preview without creating"#)]
    Sync {
        #[command(subcommand)]
        action: sync::SyncCommands,
    },
    /// Manage issue statuses - view workflow states
    #[command(alias = "st")]
    #[command(after_help = r#"EXAMPLES:
    linear statuses list -t ENG             # List team statuses
    linear st get "In Progress" -t ENG      # View status details"#)]
    Statuses {
        #[command(subcommand)]
        action: statuses::StatusCommands,
    },
    /// Git branch operations - checkout branches, create PRs
    #[command(alias = "g")]
    #[command(after_help = r#"EXAMPLES:
    linear git checkout LIN-123             # Checkout issue branch
    linear g branch LIN-123                 # Show branch name
    linear g pr LIN-123                     # Create GitHub PR
    linear g pr LIN-123 --draft             # Create draft PR"#)]
    Git {
        #[command(subcommand)]
        action: git::GitCommands,
    },
    /// Bulk operations - update multiple issues at once
    #[command(alias = "b")]
    #[command(after_help = r#"EXAMPLES:
    linear bulk update -s Done LIN-1 LIN-2  # Update multiple issues
    linear b assign --user me LIN-1 LIN-2   # Assign multiple issues
    linear b label --add bug LIN-1 LIN-2    # Add label to issues"#)]
    Bulk {
        #[command(subcommand)]
        action: bulk::BulkCommands,
    },
    /// Manage cache - clear cached data or view status
    #[command(alias = "ca")]
    #[command(after_help = r#"EXAMPLES:
    linear cache status                     # Show cache status
    linear ca clear                         # Clear all cache
    linear ca clear --type teams            # Clear only teams cache"#)]
    Cache {
        #[command(subcommand)]
        action: commands::cache::CacheCommands,
    },
    /// Manage notifications - view and mark as read
    #[command(alias = "n")]
    #[command(after_help = r#"EXAMPLES:
    linear notifications list               # List unread notifications
    linear n count                          # Show unread count
    linear n read-all                       # Mark all as read
    linear n archive NOTIF_ID              # Archive a notification
    linear n archive-all                   # Archive all notifications"#)]
    Notifications {
        #[command(subcommand)]
        action: notifications::NotificationCommands,
    },
    /// Manage issue templates - create and use templates
    #[command(alias = "tpl")]
    #[command(after_help = r#"EXAMPLES:
    linear templates list                   # List all templates
    linear tpl create bug                   # Create a new template
    linear tpl show bug                     # View template details"#)]
    Templates {
        #[command(subcommand)]
        action: templates::TemplateCommands,
    },
    /// Time tracking - log and view time entries
    #[command(alias = "tm")]
    #[command(after_help = r#"EXAMPLES:
    linear time log LIN-123 2h              # Log 2 hours on issue
    linear tm list --issue LIN-123          # List time entries"#)]
    Time {
        #[command(subcommand)]
        action: time::TimeCommands,
    },
    /// Fetch uploads from Linear with authentication
    #[command(alias = "up")]
    #[command(after_help = r#"EXAMPLES:
    linear uploads fetch URL                # Output to stdout (for piping)
    linear up fetch URL -f file.png         # Save to file
    linear up fetch URL | base64            # Pipe to another tool"#)]
    Uploads {
        #[command(subcommand)]
        action: uploads::UploadCommands,
    },
    /// Interactive mode - TUI for browsing and managing issues
    #[command(alias = "int")]
    #[command(after_help = r#"EXAMPLES:
    linear interactive                      # Launch interactive mode
    linear interactive --team ENG           # Preselect team

Use arrow keys to navigate, Enter to select, q to quit."#)]
    Interactive {
        /// Preselect team by key, name, or ID
        #[arg(short, long)]
        team: Option<String>,
    },
    /// Detect current Linear issue from git branch - for AI agents
    #[command(alias = "ctx")]
    #[command(after_help = r#"EXAMPLES:
    linear context                          # Show current issue from branch
    linear ctx --output json                # Get as JSON for parsing

Detects issue ID from branch names like:
  - lin-123-fix-bug
  - feature/LIN-456-new-feature
  - scw-789-some-task"#)]
    Context,
    /// Manage favorites - quick access to issues/projects
    #[command(alias = "fav")]
    #[command(after_help = r#"EXAMPLES:
    linear favorites list                   # List favorites
    linear fav add LIN-123                  # Add issue to favorites
    linear fav remove LIN-123               # Remove from favorites"#)]
    Favorites {
        #[command(subcommand)]
        action: favorites::FavoriteCommands,
    },
    /// Manage roadmaps - view and manage roadmap planning
    #[command(alias = "rm")]
    #[command(after_help = r#"EXAMPLES:
    linear roadmaps list                    # List all roadmaps
    linear rm get ROADMAP_ID                # View roadmap details
    linear rm create "Q1 Plan"              # Create a roadmap
    linear rm update ID -n "Q2 Plan"        # Update roadmap name"#)]
    Roadmaps {
        #[command(subcommand)]
        action: roadmaps::RoadmapCommands,
    },
    /// Manage initiatives - create, update, and track initiatives
    #[command(alias = "init")]
    #[command(after_help = r#"EXAMPLES:
    linear initiatives list                 # List all initiatives
    linear init get INITIATIVE_ID           # View initiative details
    linear init create "H1 Goals"           # Create an initiative
    linear init update ID -s "Active"       # Update initiative status"#)]
    Initiatives {
        #[command(subcommand)]
        action: initiatives::InitiativeCommands,
    },
    /// Triage inbox - manage unassigned issues
    #[command(alias = "tr")]
    #[command(after_help = r#"EXAMPLES:
    linear triage list                      # List triage issues
    linear tr claim LIN-123                 # Claim an issue
    linear tr snooze LIN-123 --duration 1w  # Snooze for a week"#)]
    Triage {
        #[command(subcommand)]
        action: triage::TriageCommands,
    },
    /// View metrics - velocity, burndown, progress
    #[command(alias = "mt")]
    #[command(after_help = r#"EXAMPLES:
    linear metrics cycle CYCLE_ID           # Cycle metrics
    linear mt project PROJECT_ID            # Project progress
    linear mt velocity TEAM --cycles 5      # Team velocity"#)]
    Metrics {
        #[command(subcommand)]
        action: metrics::MetricsCommands,
    },
    /// Manage project milestones - list, create, update, delete milestones
    #[command(alias = "ms")]
    #[command(after_help = r#"EXAMPLES:
    linear milestones list -p "My Project"  # List milestones
    linear ms get MILESTONE_ID              # View milestone details
    linear ms create "Beta Release" -p PROJ # Create milestone
    linear ms update ID --target-date +2w   # Update target date
    linear ms delete ID --force             # Delete milestone"#)]
    Milestones {
        #[command(subcommand)]
        action: commands::milestones::MilestoneCommands,
    },
    /// Export issues to CSV, JSON, or Markdown
    #[command(alias = "exp")]
    #[command(after_help = r#"EXAMPLES:
    linear export csv --team ENG            # Export team issues to CSV
    linear exp csv -f issues.csv            # Export to file
    linear exp json --team ENG --pretty     # Export as pretty JSON
    linear exp markdown --team ENG          # Export as Markdown
    linear exp projects-csv -f projects.csv # Export projects to CSV"#)]
    Export {
        #[command(subcommand)]
        action: export::ExportCommands,
    },
    /// Import issues from CSV or JSON files
    #[command(alias = "im")]
    #[command(after_help = r#"EXAMPLES:
    linear import csv issues.csv -t ENG           # Import from CSV
    linear im csv issues.csv -t ENG --dry-run     # Preview without creating
    linear im json issues.json -t ENG             # Import from JSON"#)]
    Import {
        #[command(subcommand)]
        action: import::ImportCommands,
    },
    /// View issue history and activity
    #[command(alias = "hist")]
    #[command(after_help = r#"EXAMPLES:
    linear history issue LIN-123            # View issue activity
    linear hist issue LIN-123 --limit 50    # More entries"#)]
    History {
        #[command(subcommand)]
        action: history::HistoryCommands,
    },
    /// Manage custom views - create, apply, and manage saved views
    #[command(alias = "v")]
    #[command(after_help = r#"EXAMPLES:
    linear views list                       # List all custom views
    linear v list --shared                  # List shared views only
    linear v get "My View"                  # View details
    linear v create "Bug Triage" --shared   # Create a shared view
    linear v delete VIEW_ID --force         # Delete a view"#)]
    Views {
        #[command(subcommand)]
        action: views::ViewCommands,
    },
    /// Manage webhooks - create, update, delete, listen for events
    #[command(alias = "wh")]
    #[command(after_help = r#"EXAMPLES:
    linear webhooks list                    # List all webhooks
    linear wh create URL --events Issue     # Create webhook
    linear wh delete WEBHOOK_ID --force     # Delete webhook
    linear wh rotate-secret WEBHOOK_ID      # Rotate webhook secret
    linear wh listen --port 9000            # Listen for events locally"#)]
    Webhooks {
        #[command(subcommand)]
        action: webhooks::WebhookCommands,
    },
    /// Watch for updates (polling)
    #[command(after_help = r#"EXAMPLES:
    linear watch issue LIN-123             # Watch single issue
    linear watch issue LIN-123 --interval 30  # Poll every 30 seconds
    linear watch project PROJECT_ID        # Watch a project
    linear watch team ENG                  # Watch a team"#)]
    Watch {
        #[command(subcommand)]
        action: WatchCommands,
    },
    /// Manage issue relationships - parent/child, blocking, related
    #[command(alias = "rel")]
    #[command(after_help = r#"EXAMPLES:
    linear relations list LIN-123           # List issue relationships
    linear rel add LIN-1 -r blocks LIN-2    # LIN-1 blocks LIN-2
    linear rel parent LIN-2 LIN-1           # Set LIN-1 as parent of LIN-2
    linear rel unparent LIN-2               # Remove parent"#)]
    Relations {
        #[command(subcommand)]
        action: relations::RelationCommands,
    },
    /// Show current authenticated user (alias for `users me`)
    #[command(alias = "me")]
    Whoami,
    /// Mark the current branch's issue as Done
    #[command(after_help = r#"EXAMPLES:
    linear done                              # Mark current branch issue as Done
    linear done --status "In Progress"       # Set to specific status instead

Reads the current git branch, extracts the issue ID (e.g. feat/SCW-123-title → SCW-123),
and updates the issue status."#)]
    Done {
        /// Status to set (default: "Done")
        #[arg(short, long, default_value = "Done")]
        status: String,
    },
    /// Guided onboarding wizard - configure auth, team, and output format
    #[command(after_help = r#"EXAMPLES:
    linear setup                             # Run interactive setup wizard

Walks you through:
  1. Setting your Linear API key
  2. Choosing a default team
  3. Selecting output format (table or json)"#)]
    Setup,
    /// Sprint planning - manage cycle-based sprints
    #[command(alias = "sp")]
    #[command(after_help = r#"EXAMPLES:
    linear sprint status -t ENG            # Current sprint status
    linear sp progress -t ENG              # Sprint progress bar
    linear sp plan -t ENG                  # Next sprint's planned issues
    linear sp carry-over -t ENG --force    # Move incomplete issues to next cycle"#)]
    Sprint {
        #[command(subcommand)]
        action: sprint::SprintCommands,
    },
    /// Generate shell completions
    #[command(alias = "comp")]
    #[command(after_help = r#"EXAMPLES:
    linear completions bash > ~/.bash_completion.d/linear
    linear completions zsh > ~/.zfunc/_linear
    linear completions fish > ~/.config/fish/completions/linear.fish
    linear comp powershell > linear.ps1
    linear comp dynamic bash   # Dynamic completions with argument value hints
    linear comp dynamic zsh    # Dynamic completions for zsh"#)]
    Completions {
        #[command(subcommand)]
        action: CompletionCommands,
    },
    /// Internal: provide dynamic completion values (hidden from help)
    #[command(name = "_complete", hide = true)]
    Complete {
        /// What to complete: teams, projects, issues, statuses, users, labels
        #[arg(long = "type")]
        type_: String,
        /// Partial input to filter
        #[arg(long, default_value = "")]
        prefix: String,
        /// Team context for scoped completions (e.g. statuses)
        #[arg(long)]
        team: Option<String>,
    },
    /// Configure CLI settings - API keys and workspaces
    #[command(after_help = r#"EXAMPLES:
    linear config set-key YOUR_API_KEY      # Set API key
    linear config set api-key YOUR_API_KEY  # Set API key (alt)
    linear config get api-key               # Get API key (masked)
    linear config set profile work          # Switch profile
    linear config show                      # Show configuration
    linear config workspace-add work KEY    # Add workspace
    linear config workspace-switch work     # Switch workspace"#)]
    Config {
        #[command(subcommand)]
        action: ConfigCommands,
    },
}

#[derive(Subcommand)]
enum ConfigCommands {
    /// Set API key
    #[command(after_help = r#"EXAMPLE:
    linear config set-key lin_api_xxxxxxxxxxxxx"#)]
    SetKey {
        /// Your Linear API key
        key: String,
    },
    /// Get a configuration value
    Get {
        /// Config key to retrieve (api-key, profile)
        key: String,
        /// Output raw value without masking
        #[arg(long)]
        raw: bool,
    },
    /// Set a configuration value
    Set {
        /// Config key to set (api-key, profile)
        key: String,
        /// Value to set
        value: String,
    },
    /// Show current configuration
    Show,
    /// Generate shell completions
    #[command(after_help = r#"EXAMPLES:
    linear config completions bash > ~/.bash_completion.d/linear
    linear config completions zsh > ~/.zfunc/_linear
    linear config completions fish > ~/.config/fish/completions/linear.fish
    linear config completions powershell > linear.ps1"#)]
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },
    /// Add a new workspace
    #[command(alias = "add")]
    #[command(after_help = r#"EXAMPLE:
    linear config workspace-add personal lin_api_xxxxxxxxxxxxx"#)]
    WorkspaceAdd {
        /// Workspace name
        name: String,
        /// API key for this workspace
        api_key: String,
    },
    /// List all workspaces
    #[command(alias = "list")]
    WorkspaceList,
    /// Switch to a different workspace
    #[command(alias = "use")]
    #[command(after_help = r#"EXAMPLE:
    linear config workspace-switch personal"#)]
    WorkspaceSwitch {
        /// Workspace name to switch to
        name: String,
    },
    /// Show current workspace
    #[command(alias = "current")]
    WorkspaceCurrent,
    /// Remove a workspace
    #[command(alias = "rm")]
    WorkspaceRemove {
        /// Workspace name to remove
        name: String,
    },
}

#[derive(Subcommand)]
enum WatchCommands {
    /// Watch an issue for updates
    Issue {
        /// Issue identifier to watch
        id: String,
        /// Polling interval in seconds
        #[arg(short, long, default_value = "10")]
        interval: u64,
    },
    /// Watch a project for updates
    Project {
        /// Project ID to watch
        id: String,
        /// Polling interval in seconds
        #[arg(short, long, default_value = "10")]
        interval: u64,
    },
    /// Watch a team for updates
    Team {
        /// Team key or ID to watch
        team: String,
        /// Polling interval in seconds
        #[arg(short, long, default_value = "10")]
        interval: u64,
    },
}

#[derive(Subcommand)]
enum CompletionCommands {
    /// Generate static shell completions (command names and flags)
    Static {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },
    /// Generate dynamic shell completions (argument values from Linear API)
    Dynamic {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: Shell,
    },
}

fn main() -> Result<()> {
    // Spawn with 8 MB stack to accommodate clap derive macro stack usage
    // with many subcommand variants (default 1 MB overflows in debug builds).
    let builder = std::thread::Builder::new().stack_size(8 * 1024 * 1024);
    let handler = builder.spawn(|| {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("Failed to create tokio runtime")
            .block_on(async_main())
    })?;
    handler.join().unwrap()
}

async fn async_main() -> Result<()> {
    let cli = Cli::parse();
    if cli.no_color || cli.color_mode == ColorChoice::Never {
        colored::control::set_override(false);
    } else if cli.color_mode == ColorChoice::Always {
        colored::control::set_override(true);
    }
    set_cli_state(DisplayOptions {
        width: cli.width,
        no_truncate: cli.no_truncate,
    });
    if let Some(key) = cli.api_key.as_deref() {
        std::env::set_var("LINEAR_API_KEY", key);
    }
    if let Some(profile) = cli.profile.as_deref() {
        std::env::set_var("LINEAR_CLI_PROFILE", profile);
    }
    api::set_default_retry(cli.retry);
    let filters = parse_filters(&cli.filter)?;
    let pagination = PaginationOptions {
        limit: cli.limit,
        after: cli.after.clone(),
        before: cli.before.clone(),
        page_size: cli.page_size,
        all: cli.all,
    };
    let json_opts = JsonOutputOptions::new(
        cli.compact,
        if cli.fields.is_empty() {
            None
        } else {
            Some(cli.fields.clone())
        },
        cli.sort.clone(),
        cli.order,
        true,
    );
    let output = OutputOptions {
        format: cli.output,
        json: json_opts,
        format_template: cli.format.clone(),
        filters,
        fail_on_empty: cli.fail_on_empty,
        pagination,
        cache: cache::CacheOptions {
            ttl_seconds: cli.cache_ttl,
            no_cache: cli.no_cache,
        },
        dry_run: cli.dry_run,
    };
    let agent_opts = AgentOptions {
        quiet: cli.quiet,
        id_only: cli.id_only,
        dry_run: cli.dry_run,
        yes: cli.yes,
    };

    output::set_quiet_mode(
        cli.quiet || matches!(cli.output, OutputFormat::Json | OutputFormat::Ndjson),
    );
    set_yes_mode(cli.yes);

    if cli.schema {
        let schema = serde_json::json!({
            "schema_version": "1.0",
            "schema_file": "docs/json/schema.json",
        });
        if matches!(cli.output, OutputFormat::Ndjson) || cli.compact {
            println!("{}", serde_json::to_string(&schema)?);
        } else {
            println!("{}", serde_json::to_string_pretty(&schema)?);
        }
        std::process::exit(0);
    }

    // Set up pager for table output when stdout is a terminal
    let _pager_guard = if should_use_pager(cli.no_pager, &cli.output, cli.quiet) {
        setup_pager()
    } else {
        None
    };

    let result = run_command(cli.command, &output, agent_opts, cli.retry).await;

    match result {
        Ok(()) => std::process::exit(0),
        Err(e) => {
            // Check if JSON output requested for structured errors
            if output.is_json() {
                if let Some(cli_error) = e.downcast_ref::<CliError>() {
                    let error_json = serde_json::json!({
                        "error": true,
                        "message": cli_error.message,
                        "code": cli_error.code(),
                        "details": cli_error.details,
                        "retry_after": cli_error.retry_after,
                    });
                    eprintln!(
                        "{}",
                        serde_json::to_string(&error_json).unwrap_or_else(|_| e.to_string())
                    );
                } else {
                    let error_json = serde_json::json!({
                        "error": true,
                        "message": e.to_string(),
                        "code": categorize_error(&e),
                        "details": null,
                        "retry_after": null,
                    });
                    eprintln!(
                        "{}",
                        serde_json::to_string(&error_json).unwrap_or_else(|_| e.to_string())
                    );
                }
            } else {
                eprintln!("Error: {}", e);
            }
            std::process::exit(categorize_error(&e) as i32);
        }
    }

    #[allow(unreachable_code)]
    Ok(())
}

/// Categorize error for exit codes: 1=general error, 2=not found, 3=auth error
fn categorize_error(e: &anyhow::Error) -> u8 {
    if let Some(cli_error) = e.downcast_ref::<CliError>() {
        return cli_error.code();
    }
    let msg = e.to_string().to_lowercase();
    if msg.contains("not found") || msg.contains("does not exist") {
        2
    } else if msg.contains("unauthorized")
        || msg.contains("api key")
        || msg.contains("authentication")
    {
        3
    } else if msg.contains("rate limit") || msg.contains("too many requests") {
        4
    } else {
        1
    }
}

async fn run_command(
    command: Commands,
    output: &OutputOptions,
    agent_opts: AgentOptions,
    retry: u32,
) -> Result<()> {
    match command {
        Commands::Common => {
            println!("Common tasks:");
            println!("  linear issues list -t ENG");
            println!("  linear issues get LIN-123");
            println!("  linear issues create \"Title\" -t ENG");
            println!("  linear issues update LIN-123 -s Done");
            println!("  linear projects list");
            println!("  linear teams list");
            println!("  linear git checkout LIN-123");
            println!("  linear git pr LIN-123 --draft");
            println!("  linear interactive --team ENG");
            println!();
            println!("Tips:");
            println!("  Use --help after any command for more options.");
            println!("  Use --output json or --output ndjson for scripting/LLMs.");
            println!("  Use --no-color for logs/CI.");
            println!("  Use --limit/--page-size/--all for pagination.");
        }
        Commands::Agent => {
            println!("Agent harness:");
            println!("  Use --output json or --output ndjson for machine-readable output.");
            println!("  Use --compact and --fields to reduce tokens.");
            println!("  Use --sort/--order to stabilize list outputs.");
            println!("  Use --filter to reduce list results.");
            println!("  Use --id-only for chaining create/update commands.");
            println!("  Use --data - for JSON input on issue create/update.");
            println!("  Use --yes to auto-confirm all prompts (deletes, destructive ops).");
            println!("  Use 'linear done' to mark current branch's issue as Done.");
            println!();
            println!("Examples:");
            println!("  linear issues list --output json --compact --fields identifier,title");
            println!("  linear issues list --output ndjson --filter state.name=In\\ Progress");
            println!("  linear issues get LIN-123 --output json");
            println!("  linear issues update LIN-123 --data - --dry-run");
            println!("  linear context --output json --id-only");
            println!();
            println!("Schemas:");
            println!("  See docs/json/ for sample outputs.");
            println!("  Use --schema to print the current schema version.");
        }
        Commands::Projects { action } => projects::handle(action, output).await?,
        Commands::ProjectUpdates { action } => project_updates::handle(action, output).await?,
        Commands::Issues { action } => issues::handle(action, output, agent_opts).await?,
        Commands::Attachments { action } => attachments::handle(action, output).await?,
        Commands::Labels { action } => labels::handle(action, output).await?,
        Commands::Teams { action } => teams::handle(action, output).await?,
        Commands::Users { action } => users::handle(action, output).await?,
        Commands::Cycles { action } => cycles::handle(action, output).await?,
        Commands::Comments { action } => comments::handle(action, output).await?,
        Commands::Documents { action } => documents::handle(action, output).await?,
        Commands::Search { action } => search::handle(action, output).await?,
        Commands::Sync { action } => sync::handle(action, output).await?,
        Commands::Statuses { action } => statuses::handle(action, output).await?,
        Commands::Git { action } => git::handle(action).await?,
        Commands::Bulk { action } => bulk::handle(action, output).await?,
        Commands::Cache { action } => commands::cache::handle(action).await?,
        Commands::Notifications { action } => notifications::handle(action, output).await?,
        Commands::Templates { action } => templates::handle(action, output).await?,
        Commands::Time { action } => time::handle(action, output).await?,
        Commands::Uploads { action } => uploads::handle(action).await?,
        Commands::Interactive { team } => interactive::run(team).await?,
        Commands::Context => handle_context(output, agent_opts, retry).await?,
        Commands::Favorites { action } => favorites::handle(action, output).await?,
        Commands::Roadmaps { action } => {
            roadmaps::handle(action, output, &output.pagination).await?
        }
        Commands::Initiatives { action } => {
            initiatives::handle(action, output, &output.pagination).await?
        }
        Commands::Triage { action } => triage::handle(action, output).await?,
        Commands::Metrics { action } => metrics::handle(action, output).await?,
        Commands::Milestones { action } => commands::milestones::handle(action, output).await?,
        Commands::Export { action } => export::handle(action, output).await?,
        Commands::Import { action } => import::handle(action, output).await?,
        Commands::History { action } => history::handle(action, output).await?,
        Commands::Views { action } => views::handle(action, output).await?,
        Commands::Webhooks { action } => webhooks::handle(action, output).await?,
        Commands::Watch { action } => match action {
            WatchCommands::Issue { id, interval } => {
                watch::watch_issue(&id, interval, output).await?
            }
            WatchCommands::Project { id, interval } => {
                watch::watch_project(&id, interval, output).await?
            }
            WatchCommands::Team { team, interval } => {
                watch::watch_team(&team, interval, output).await?
            }
        },
        Commands::Relations { action } => relations::handle(action, output).await?,
        Commands::Whoami => users::handle(users::UserCommands::Me, output).await?,
        Commands::Done { status } => handle_done(&status, output, agent_opts, retry).await?,
        Commands::Setup => handle_setup(output).await?,
        Commands::Sprint { action } => sprint::handle(action, output).await?,
        Commands::Completions { action } => match action {
            CompletionCommands::Static { shell } => {
                let mut cmd = Cli::command();
                generate(shell, &mut cmd, "linear-cli", &mut std::io::stdout());
            }
            CompletionCommands::Dynamic { shell } => {
                print_dynamic_completion_script(shell);
            }
        },
        Commands::Complete {
            type_,
            prefix,
            team,
        } => handle_complete(&type_, &prefix, team.as_deref()).await?,
        Commands::Auth { action } => auth::handle(action, output).await?,
        Commands::Api { action } => commands::api::handle(action, output).await?,
        Commands::Doctor { check_api, fix } => doctor::run(output, check_api, fix).await?,
        Commands::Config { action } => match action {
            ConfigCommands::SetKey { key } => {
                config::set_api_key(&key)?;
                if !agent_opts.quiet {
                    println!("API key saved successfully!");
                }
            }
            ConfigCommands::Get { key, raw } => {
                config::config_get(&key, raw)?;
            }
            ConfigCommands::Set { key, value } => {
                config::config_set(&key, &value)?;
            }
            ConfigCommands::Show => {
                config::show_config()?;
            }
            ConfigCommands::Completions { shell } => {
                let mut cmd = Cli::command();
                generate(shell, &mut cmd, "linear-cli", &mut std::io::stdout());
            }
            ConfigCommands::WorkspaceAdd { name, api_key } => {
                config::workspace_add(&name, &api_key)?;
            }
            ConfigCommands::WorkspaceList => {
                config::workspace_list()?;
            }
            ConfigCommands::WorkspaceSwitch { name } => {
                config::workspace_switch(&name)?;
            }
            ConfigCommands::WorkspaceCurrent => {
                config::workspace_current()?;
            }
            ConfigCommands::WorkspaceRemove { name } => {
                config::workspace_remove(&name)?;
            }
        },
    }

    Ok(())
}

/// Determine if pager should be used
fn should_use_pager(no_pager: bool, format: &OutputFormat, quiet: bool) -> bool {
    if no_pager || quiet {
        return false;
    }
    // Only page table output, not JSON/NDJSON (those are for scripts)
    if !matches!(format, OutputFormat::Table) {
        return false;
    }
    // Only page when stdout is a terminal
    std::io::stdout().is_terminal()
}

/// Set up pager by spawning pager process and redirecting stdout.
/// Returns a guard that waits for the pager to finish when dropped.
fn setup_pager() -> Option<PagerGuard> {
    // Set LESS options if not already set (like git does)
    // -R: raw control chars (colors), -X: don't clear screen, -F: quit if one screen
    if std::env::var("LESS").is_err() {
        std::env::set_var("LESS", "-R -X -F");
    }

    let pager_cmd = std::env::var("PAGER").unwrap_or_else(|_| "less".to_string());
    if pager_cmd == "cat" || pager_cmd.is_empty() {
        return None;
    }

    // Split pager command to support args (e.g. PAGER="less -FRX")
    let mut parts = pager_cmd.split_whitespace();
    let program = parts.next()?;
    let args: Vec<&str> = parts.collect();

    // Try to spawn pager with stdin piped
    let mut child = match std::process::Command::new(program)
        .args(&args)
        .stdin(std::process::Stdio::piped())
        .spawn()
    {
        Ok(child) => child,
        Err(_) => return None, // Pager not available, continue without it
    };

    let child_stdin = child.stdin.take()?;

    // Redirect stdout (fd 1) to the pager's stdin using dup2.
    #[cfg(unix)]
    {
        use std::os::unix::io::AsRawFd;
        let pager_fd = child_stdin.as_raw_fd();
        unsafe { libc::dup2(pager_fd, 1); }
        Some(PagerGuard {
            child,
            _stdin: Some(child_stdin),
        })
    }

    #[cfg(not(unix))]
    {
        // On non-Unix platforms, pager redirect is not supported — skip
        drop(child_stdin);
        let _ = child.kill();
        None
    }
}

/// Guard that waits for the pager process to exit when dropped
struct PagerGuard {
    child: std::process::Child,
    _stdin: Option<std::process::ChildStdin>,
}

impl Drop for PagerGuard {
    fn drop(&mut self) {
        // Close stdin pipe first so the pager knows we're done
        self._stdin.take();
        // Then wait for pager to finish
        let _ = self.child.wait();
    }
}

/// Handle the context command - detect current Linear issue from git branch
async fn handle_context(
    output: &OutputOptions,
    agent_opts: AgentOptions,
    retry: u32,
) -> Result<()> {
    // Get current git branch
    let branch_output = std::process::Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output();

    let branch = match branch_output {
        Ok(output) if output.status.success() => {
            String::from_utf8_lossy(&output.stdout).trim().to_string()
        }
        _ => {
            anyhow::bail!("Not in a git repository or git not available");
        }
    };

    // Extract issue ID from branch name using regex
    static ISSUE_RE: OnceLock<regex::Regex> = OnceLock::new();
    let re = ISSUE_RE.get_or_init(|| regex::Regex::new(r"(?i)([a-z]+-\d+)").unwrap());

    let issue_id = re
        .find(&branch)
        .map(|m| m.as_str().to_uppercase())
        .ok_or_else(|| anyhow::anyhow!("No Linear issue ID found in branch: {}", branch))?;

    if output.is_json() || output.has_template() {
        if agent_opts.id_only {
            print_json_owned(serde_json::json!(issue_id), output)?;
            return Ok(());
        }
        // Fetch issue details for JSON output
        let client = api::LinearClient::new_with_retry(retry)?;
        let query = r#"
            query($id: String!) {
                issue(id: $id) {
                    id
                    identifier
                    title
                    state { name }
                    assignee { name }
                    priority
                    url
                }
            }
        "#;

        let result = client
            .query(query, Some(serde_json::json!({ "id": issue_id })))
            .await;

        match result {
            Ok(data) => {
                let issue = &data["data"]["issue"];
                if issue.is_null() {
                    print_json_owned(
                        serde_json::json!({
                            "branch": branch,
                            "issue_id": issue_id,
                            "found": false,
                        }),
                        output,
                    )?;
                } else {
                    print_json_owned(
                        serde_json::json!({
                            "branch": branch,
                            "issue_id": issue_id,
                            "found": true,
                            "issue": issue,
                        }),
                        output,
                    )?;
                }
            }
            Err(_) => {
                print_json_owned(
                    serde_json::json!({
                        "branch": branch,
                        "issue_id": issue_id,
                        "found": false,
                    }),
                    output,
                )?;
            }
        }
    } else {
        println!("{}", issue_id);
    }

    Ok(())
}

/// Handle the `done` command — mark the current branch's issue as Done (or a custom status)
async fn handle_done(
    status: &str,
    output: &OutputOptions,
    agent_opts: AgentOptions,
    retry: u32,
) -> Result<()> {
    // Get current git branch
    let branch_output = std::process::Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output();

    let branch = match branch_output {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
        _ => {
            anyhow::bail!("Not in a git repository or git not available");
        }
    };

    // Extract issue ID from branch name
    static DONE_ISSUE_RE: OnceLock<regex::Regex> = OnceLock::new();
    let re = DONE_ISSUE_RE.get_or_init(|| regex::Regex::new(r"(?i)([a-z]+-\d+)").unwrap());

    let issue_id = re
        .find(&branch)
        .map(|m| m.as_str().to_uppercase())
        .ok_or_else(|| anyhow::anyhow!("No Linear issue ID found in branch: {}", branch))?;

    if output.dry_run {
        if output.is_json() || output.has_template() {
            print_json_owned(
                serde_json::json!({
                    "dry_run": true,
                    "would_update": {
                        "issue_id": issue_id,
                        "status": status,
                    }
                }),
                output,
            )?;
        } else {
            println!("[DRY RUN] Would set {} to status: {}", issue_id, status);
        }
        return Ok(());
    }

    let client = api::LinearClient::new_with_retry(retry)?;

    // Get the issue's team to resolve the correct state
    let query = r#"
        query($id: String!) {
            issue(id: $id) {
                id
                identifier
                title
                team { id }
            }
        }
    "#;

    let result = client
        .query(query, Some(serde_json::json!({ "id": issue_id })))
        .await?;
    let issue = &result["data"]["issue"];
    if issue.is_null() {
        anyhow::bail!("Issue not found: {}", issue_id);
    }

    let team_id = issue["team"]["id"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("Could not determine team for {}", issue_id))?;

    let state_id = api::resolve_state_id(&client, team_id, status).await?;

    let mutation = r#"
        mutation($id: String!, $stateId: String!) {
            issueUpdate(id: $id, input: { stateId: $stateId }) {
                success
                issue {
                    id
                    identifier
                    title
                    state { name }
                }
            }
        }
    "#;

    let result = client
        .mutate(
            mutation,
            Some(serde_json::json!({ "id": issue_id, "stateId": state_id })),
        )
        .await?;

    let success = result["data"]["issueUpdate"]["success"]
        .as_bool()
        .unwrap_or(false);

    if !success {
        anyhow::bail!("Failed to update issue {}", issue_id);
    }

    if output.is_json() || output.has_template() {
        let updated = &result["data"]["issueUpdate"]["issue"];
        print_json_owned(
            serde_json::json!({
                "issue_id": issue_id,
                "status": status,
                "updated": updated,
            }),
            output,
        )?;
    } else if !agent_opts.quiet {
        let identifier = result["data"]["issueUpdate"]["issue"]["identifier"]
            .as_str()
            .unwrap_or(&issue_id);
        let new_state = result["data"]["issueUpdate"]["issue"]["state"]["name"]
            .as_str()
            .unwrap_or(status);
        println!("+ {} -> {}", identifier, new_state);
    }

    Ok(())
}

/// Handle the `setup` command — guided onboarding wizard
async fn handle_setup(output: &OutputOptions) -> Result<()> {
    use std::io::{self, Write};

    println!("Linear CLI Setup");
    println!("{}", "-".repeat(40));
    println!();

    // Step 1: API Key
    println!("Step 1: Authentication");
    println!("  Get your API key from: https://linear.app/settings/api");
    println!();
    print!("  Enter your Linear API key: ");
    io::stdout().flush()?;

    let mut api_key = String::new();
    io::stdin().read_line(&mut api_key)?;
    let api_key = api_key.trim().to_string();

    if api_key.is_empty() {
        anyhow::bail!("API key cannot be empty");
    }

    config::set_api_key(&api_key)?;
    println!("  API key saved.");
    println!();

    // Step 2: Validate the key and pick default team
    println!("Step 2: Default Team");
    let client = api::LinearClient::new()?;

    let teams_query = r#"
        query {
            teams {
                nodes {
                    id
                    name
                    key
                }
            }
        }
    "#;

    match client.query(teams_query, None).await {
        Ok(data) => {
            let teams = &data["data"]["teams"]["nodes"];
            if let Some(teams_arr) = teams.as_array() {
                if teams_arr.is_empty() {
                    println!("  No teams found. Skipping default team.");
                } else {
                    println!("  Available teams:");
                    for (i, team) in teams_arr.iter().enumerate() {
                        let key = team["key"].as_str().unwrap_or("?");
                        let name = team["name"].as_str().unwrap_or("?");
                        println!("    {}. {} ({})", i + 1, name, key);
                    }
                    println!();
                    print!("  Select team number (or press Enter to skip): ");
                    io::stdout().flush()?;

                    let mut choice = String::new();
                    io::stdin().read_line(&mut choice)?;
                    let choice = choice.trim();

                    if !choice.is_empty() {
                        if let Ok(num) = choice.parse::<usize>() {
                            if num >= 1 && num <= teams_arr.len() {
                                let team = &teams_arr[num - 1];
                                let key = team["key"].as_str().unwrap_or("?");
                                println!("  Default team: {}", key);
                                println!("  Tip: Use -t {} or set LINEAR_CLI_TEAM={}", key, key);
                            } else {
                                println!("  Invalid selection, skipping.");
                            }
                        } else {
                            println!("  Invalid input, skipping.");
                        }
                    }
                }
            }
        }
        Err(e) => {
            println!("  Could not fetch teams (API key may be invalid): {}", e);
            println!("  Run 'linear doctor --check-api' to diagnose.");
        }
    }

    println!();

    // Step 3: Output format
    println!("Step 3: Output Format");
    println!("  1. table (default, human-readable)");
    println!("  2. json (machine-readable, for scripts/agents)");
    println!();
    print!("  Select format [1]: ");
    io::stdout().flush()?;

    let mut format_choice = String::new();
    io::stdin().read_line(&mut format_choice)?;
    let format_choice = format_choice.trim();

    match format_choice {
        "2" | "json" => {
            println!("  Output format: json");
            println!("  Tip: Set LINEAR_CLI_OUTPUT=json in your shell profile.");
        }
        _ => {
            println!("  Output format: table (default)");
        }
    }

    println!();
    println!("Setup complete!");

    if output.is_json() || output.has_template() {
        print_json_owned(
            serde_json::json!({
                "setup": true,
                "api_key_saved": true,
            }),
            output,
        )?;
    }

    Ok(())
}

/// Handle the hidden `_complete` command -- output dynamic completion values
async fn handle_complete(type_: &str, prefix: &str, team: Option<&str>) -> Result<()> {
    // Try to use cache first for fast completions; fall back to API
    let cache = cache::Cache::new().ok();

    match type_ {
        "teams" => complete_teams(cache.as_ref(), prefix).await,
        "projects" => complete_projects(cache.as_ref(), prefix).await,
        "issues" => complete_issues(prefix).await,
        "statuses" => complete_statuses(cache.as_ref(), prefix, team).await,
        "users" => complete_users(cache.as_ref(), prefix).await,
        "labels" => complete_labels(cache.as_ref(), prefix).await,
        _ => Ok(()), // Unknown type, return empty
    }
}

/// Complete team keys with descriptions
async fn complete_teams(cache: Option<&cache::Cache>, prefix: &str) -> Result<()> {
    let teams = if let Some(data) = cache.and_then(|c| c.get(cache::CacheType::Teams)) {
        data.as_array().cloned().unwrap_or_default()
    } else {
        match fetch_teams_for_completion().await {
            Ok(t) => t,
            Err(_) => return Ok(()),
        }
    };

    let prefix_lower = prefix.to_lowercase();
    for team in &teams {
        let key = team["key"].as_str().unwrap_or("");
        let name = team["name"].as_str().unwrap_or("");
        if prefix.is_empty()
            || key.to_lowercase().starts_with(&prefix_lower)
            || name.to_lowercase().starts_with(&prefix_lower)
        {
            println!("{}\t{}", key, name);
        }
    }
    Ok(())
}

/// Complete project names with descriptions
async fn complete_projects(cache: Option<&cache::Cache>, prefix: &str) -> Result<()> {
    let projects = if let Some(data) = cache.and_then(|c| c.get(cache::CacheType::Projects)) {
        data.as_array().cloned().unwrap_or_default()
    } else {
        match fetch_projects_for_completion().await {
            Ok(p) => p,
            Err(_) => return Ok(()),
        }
    };

    let prefix_lower = prefix.to_lowercase();
    for project in &projects {
        let name = project["name"].as_str().unwrap_or("");
        let state = project["state"].as_str().unwrap_or("");
        if prefix.is_empty() || name.to_lowercase().starts_with(&prefix_lower) {
            println!("{}\t{}", name, state);
        }
    }
    Ok(())
}

/// Complete issue identifiers with titles (no cache -- issues change frequently)
async fn complete_issues(prefix: &str) -> Result<()> {
    let client = match api::LinearClient::new() {
        Ok(c) => c,
        Err(_) => return Ok(()),
    };

    let query = r#"
        query($first: Int) {
            issues(first: $first, orderBy: updatedAt) {
                nodes {
                    identifier
                    title
                }
            }
        }
    "#;

    let result = match client
        .query(query, Some(serde_json::json!({ "first": 50 })))
        .await
    {
        Ok(r) => r,
        Err(_) => return Ok(()),
    };

    let empty = vec![];
    let issues = result["data"]["issues"]["nodes"]
        .as_array()
        .unwrap_or(&empty);

    let prefix_upper = prefix.to_uppercase();
    for issue in issues {
        let id = issue["identifier"].as_str().unwrap_or("");
        let title = issue["title"].as_str().unwrap_or("");
        if prefix.is_empty() || id.to_uppercase().starts_with(&prefix_upper) {
            println!("{}\t{}", id, title);
        }
    }
    Ok(())
}

/// Complete workflow state names with category
async fn complete_statuses(
    cache: Option<&cache::Cache>,
    prefix: &str,
    team: Option<&str>,
) -> Result<()> {
    let client = match api::LinearClient::new() {
        Ok(c) => c,
        Err(_) => return Ok(()),
    };

    // Resolve team to get statuses -- if no team given, try to get first team as default
    let team_id = if let Some(t) = team {
        match api::resolve_team_id(
            &client,
            t,
            &cache::CacheOptions {
                ttl_seconds: None,
                no_cache: false,
            },
        )
        .await
        {
            Ok(id) => id,
            Err(_) => return Ok(()),
        }
    } else {
        // Try to get first team as default
        let teams = if let Some(data) = cache.and_then(|c| c.get(cache::CacheType::Teams)) {
            data.as_array().cloned().unwrap_or_default()
        } else {
            match fetch_teams_for_completion().await {
                Ok(t) => t,
                Err(_) => return Ok(()),
            }
        };
        match teams.first().and_then(|t| t["id"].as_str()) {
            Some(id) => id.to_string(),
            None => return Ok(()),
        }
    };

    // Check cache for statuses
    let states =
        if let Some(cached) = cache.and_then(|c| c.get_keyed(cache::CacheType::Statuses, &team_id))
        {
            cached["states"].as_array().cloned().unwrap_or_default()
        } else {
            // Fetch from API
            let query = r#"
                query($teamId: String!) {
                    team(id: $teamId) {
                        states {
                            nodes {
                                id
                                name
                                type
                            }
                        }
                    }
                }
            "#;

            match client
                .query(query, Some(serde_json::json!({ "teamId": team_id })))
                .await
            {
                Ok(result) => result["data"]["team"]["states"]["nodes"]
                    .as_array()
                    .cloned()
                    .unwrap_or_default(),
                Err(_) => return Ok(()),
            }
        };

    let prefix_lower = prefix.to_lowercase();
    for state in &states {
        let name = state["name"].as_str().unwrap_or("");
        let type_ = state["type"].as_str().unwrap_or("");
        if prefix.is_empty() || name.to_lowercase().starts_with(&prefix_lower) {
            println!("{}\t{}", name, type_);
        }
    }
    Ok(())
}

/// Complete user display names / emails
async fn complete_users(cache: Option<&cache::Cache>, prefix: &str) -> Result<()> {
    let users = if let Some(data) = cache.and_then(|c| c.get(cache::CacheType::Users)) {
        data.as_array().cloned().unwrap_or_default()
    } else {
        match fetch_users_for_completion().await {
            Ok(u) => u,
            Err(_) => return Ok(()),
        }
    };

    let prefix_lower = prefix.to_lowercase();
    for user in &users {
        let name = user["name"].as_str().unwrap_or("");
        let email = user["email"].as_str().unwrap_or("");
        let display = if !email.is_empty() { email } else { name };
        if prefix.is_empty()
            || name.to_lowercase().starts_with(&prefix_lower)
            || email.to_lowercase().starts_with(&prefix_lower)
        {
            println!("{}\t{}", display, name);
        }
    }
    Ok(())
}

/// Complete label names
async fn complete_labels(cache: Option<&cache::Cache>, prefix: &str) -> Result<()> {
    let labels = if let Some(data) = cache.and_then(|c| c.get(cache::CacheType::Labels)) {
        data.as_array().cloned().unwrap_or_default()
    } else {
        match fetch_labels_for_completion().await {
            Ok(l) => l,
            Err(_) => return Ok(()),
        }
    };

    let prefix_lower = prefix.to_lowercase();
    for label in &labels {
        let name = label["name"].as_str().unwrap_or("");
        let color = label["color"].as_str().unwrap_or("");
        if prefix.is_empty() || name.to_lowercase().starts_with(&prefix_lower) {
            println!("{}\t{}", name, color);
        }
    }
    Ok(())
}

/// Fetch teams from API for completion (lightweight query)
async fn fetch_teams_for_completion() -> Result<Vec<serde_json::Value>> {
    let client = api::LinearClient::new()?;
    let query = r#"
        query {
            teams(first: 50) {
                nodes { id name key }
            }
        }
    "#;
    let result = client.query(query, None).await?;
    Ok(result["data"]["teams"]["nodes"]
        .as_array()
        .cloned()
        .unwrap_or_default())
}

/// Fetch projects from API for completion (lightweight query)
async fn fetch_projects_for_completion() -> Result<Vec<serde_json::Value>> {
    let client = api::LinearClient::new()?;
    let query = r#"
        query {
            projects(first: 50, orderBy: updatedAt) {
                nodes { id name state }
            }
        }
    "#;
    let result = client.query(query, None).await?;
    Ok(result["data"]["projects"]["nodes"]
        .as_array()
        .cloned()
        .unwrap_or_default())
}

/// Fetch users from API for completion (lightweight query)
async fn fetch_users_for_completion() -> Result<Vec<serde_json::Value>> {
    let client = api::LinearClient::new()?;
    let query = r#"
        query {
            users(first: 50) {
                nodes { id name email }
            }
        }
    "#;
    let result = client.query(query, None).await?;
    Ok(result["data"]["users"]["nodes"]
        .as_array()
        .cloned()
        .unwrap_or_default())
}

/// Fetch labels from API for completion (lightweight query)
async fn fetch_labels_for_completion() -> Result<Vec<serde_json::Value>> {
    let client = api::LinearClient::new()?;
    let query = r#"
        query {
            issueLabels(first: 50) {
                nodes { id name color }
            }
        }
    "#;
    let result = client.query(query, None).await?;
    Ok(result["data"]["issueLabels"]["nodes"]
        .as_array()
        .cloned()
        .unwrap_or_default())
}

/// Print shell-specific dynamic completion script
fn print_dynamic_completion_script(shell: Shell) {
    match shell {
        Shell::Bash => print!("{}", BASH_DYNAMIC_COMPLETIONS),
        Shell::Zsh => print!("{}", ZSH_DYNAMIC_COMPLETIONS),
        Shell::Fish => print!("{}", FISH_DYNAMIC_COMPLETIONS),
        Shell::PowerShell => print!("{}", POWERSHELL_DYNAMIC_COMPLETIONS),
        _ => {
            eprintln!("Dynamic completions not supported for this shell. Supported: bash, zsh, fish, powershell");
        }
    }
}

const BASH_DYNAMIC_COMPLETIONS: &str = r#"# Dynamic completions for linear-cli (bash)
# Source this file or add to ~/.bashrc:
#   eval "$(linear-cli completions dynamic bash)"

_linear_cli_dynamic() {
    local cur prev
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    # Find --team value in command line for scoped completions
    local team_val=""
    local i
    for (( i=1; i < COMP_CWORD; i++ )); do
        if [[ "${COMP_WORDS[i]}" == "-t" || "${COMP_WORDS[i]}" == "--team" ]]; then
            team_val="${COMP_WORDS[i+1]}"
            break
        fi
    done

    case "$prev" in
        -t|--team)
            local IFS=$'\n'
            COMPREPLY=($(compgen -W "$(linear-cli _complete --type teams --prefix "$cur" 2>/dev/null | cut -f1)" -- "$cur"))
            return 0
            ;;
        -s|--status)
            local team_arg=""
            if [[ -n "$team_val" ]]; then
                team_arg="--team $team_val"
            fi
            local IFS=$'\n'
            COMPREPLY=($(compgen -W "$(linear-cli _complete --type statuses --prefix "$cur" $team_arg 2>/dev/null | cut -f1)" -- "$cur"))
            return 0
            ;;
        --project)
            local IFS=$'\n'
            COMPREPLY=($(compgen -W "$(linear-cli _complete --type projects --prefix "$cur" 2>/dev/null | cut -f1)" -- "$cur"))
            return 0
            ;;
        --label|-l)
            local IFS=$'\n'
            COMPREPLY=($(compgen -W "$(linear-cli _complete --type labels --prefix "$cur" 2>/dev/null | cut -f1)" -- "$cur"))
            return 0
            ;;
        --assignee|--user)
            local IFS=$'\n'
            COMPREPLY=($(compgen -W "$(linear-cli _complete --type users --prefix "$cur" 2>/dev/null | cut -f1)" -- "$cur"))
            return 0
            ;;
    esac

    # Complete issue IDs when the previous word is a subcommand that takes an issue
    local subcmds_taking_issue="get update start close done archive unarchive comment link assign move transfer open"
    for subcmd in $subcmds_taking_issue; do
        if [[ "$prev" == "$subcmd" ]]; then
            local IFS=$'\n'
            COMPREPLY=($(compgen -W "$(linear-cli _complete --type issues --prefix "$cur" 2>/dev/null | cut -f1)" -- "$cur"))
            return 0
        fi
    done
}

# Register the dynamic completion function
complete -o default -F _linear_cli_dynamic linear-cli
"#;

const ZSH_DYNAMIC_COMPLETIONS: &str = r#"# Dynamic completions for linear-cli (zsh)
# Source this file or add to ~/.zshrc:
#   eval "$(linear-cli completions dynamic zsh)"

_linear_cli_dynamic() {
    local -a completions
    local team_val=""

    # Extract --team value from command line
    local -i i
    for (( i=2; i < CURRENT; i++ )); do
        if [[ "$words[$i]" == "-t" || "$words[$i]" == "--team" ]]; then
            team_val="$words[$((i+1))]"
            break
        fi
    done

    case "$words[$((CURRENT-1))]" in
        -t|--team)
            completions=(${(f)"$(linear-cli _complete --type teams --prefix "$words[$CURRENT]" 2>/dev/null)"})
            _describe 'team' completions
            return
            ;;
        -s|--status)
            local team_arg=""
            if [[ -n "$team_val" ]]; then
                team_arg="--team $team_val"
            fi
            completions=(${(f)"$(linear-cli _complete --type statuses --prefix "$words[$CURRENT]" ${=team_arg} 2>/dev/null)"})
            _describe 'status' completions
            return
            ;;
        --project)
            completions=(${(f)"$(linear-cli _complete --type projects --prefix "$words[$CURRENT]" 2>/dev/null)"})
            _describe 'project' completions
            return
            ;;
        --label|-l)
            completions=(${(f)"$(linear-cli _complete --type labels --prefix "$words[$CURRENT]" 2>/dev/null)"})
            _describe 'label' completions
            return
            ;;
        --assignee|--user)
            completions=(${(f)"$(linear-cli _complete --type users --prefix "$words[$CURRENT]" 2>/dev/null)"})
            _describe 'user' completions
            return
            ;;
        get|update|start|close|done|archive|unarchive|comment|link|assign|move|transfer|open)
            completions=(${(f)"$(linear-cli _complete --type issues --prefix "$words[$CURRENT]" 2>/dev/null)"})
            _describe 'issue' completions
            return
            ;;
    esac
}

compdef _linear_cli_dynamic linear-cli
"#;

const FISH_DYNAMIC_COMPLETIONS: &str = r#"# Dynamic completions for linear-cli (fish)
# Source this file or save to ~/.config/fish/completions/linear-cli-dynamic.fish:
#   linear-cli completions dynamic fish > ~/.config/fish/completions/linear-cli-dynamic.fish

# Team completions
complete -c linear-cli -l team -s t -x -a '(linear-cli _complete --type teams 2>/dev/null | string replace \t "\t")'

# Status completions (tries to pick up --team from current command line)
complete -c linear-cli -l status -s s -x -a '(linear-cli _complete --type statuses 2>/dev/null | string replace \t "\t")'

# Project completions
complete -c linear-cli -l project -x -a '(linear-cli _complete --type projects 2>/dev/null | string replace \t "\t")'

# Label completions
complete -c linear-cli -l label -s l -x -a '(linear-cli _complete --type labels 2>/dev/null | string replace \t "\t")'

# User completions
complete -c linear-cli -l assignee -x -a '(linear-cli _complete --type users 2>/dev/null | string replace \t "\t")'
complete -c linear-cli -l user -x -a '(linear-cli _complete --type users 2>/dev/null | string replace \t "\t")'

# Issue ID completions for subcommands that take an issue
for subcmd in get update start close done archive unarchive comment link assign move transfer open
    complete -c linear-cli -n "__fish_seen_subcommand_from $subcmd" -x -a '(linear-cli _complete --type issues 2>/dev/null | string replace \t "\t")'
end
"#;

const POWERSHELL_DYNAMIC_COMPLETIONS: &str = r#"# Dynamic completions for linear-cli (PowerShell)
# Source this file or add to your $PROFILE:
#   linear-cli completions dynamic powershell | Invoke-Expression

Register-ArgumentCompleter -CommandName linear-cli -ScriptBlock {
    param($commandName, $wordToComplete, $cursorPosition)

    $tokens = $wordToComplete -split '\s+'
    $prev = if ($tokens.Length -gt 1) { $tokens[-2] } else { '' }
    $current = $tokens[-1]

    # Find --team value in tokens
    $teamVal = ''
    for ($i = 0; $i -lt $tokens.Length; $i++) {
        if ($tokens[$i] -eq '-t' -or $tokens[$i] -eq '--team') {
            if ($i + 1 -lt $tokens.Length) { $teamVal = $tokens[$i + 1] }
            break
        }
    }

    $type = switch ($prev) {
        { $_ -in '-t', '--team' } { 'teams' }
        { $_ -in '-s', '--status' } { 'statuses' }
        '--project' { 'projects' }
        { $_ -in '-l', '--label' } { 'labels' }
        { $_ -in '--assignee', '--user' } { 'users' }
        { $_ -in 'get', 'update', 'start', 'close', 'done', 'archive', 'unarchive', 'comment', 'link', 'assign', 'move', 'transfer', 'open' } { 'issues' }
        default { $null }
    }

    if ($type) {
        $teamArg = if ($teamVal -and $type -eq 'statuses') { "--team $teamVal" } else { '' }
        $results = linear-cli _complete --type $type --prefix $current $teamArg 2>$null
        if ($results) {
            $results | ForEach-Object {
                $parts = $_ -split '\t', 2
                $value = $parts[0]
                $desc = if ($parts.Length -gt 1) { $parts[1] } else { '' }
                [System.Management.Automation.CompletionResult]::new($value, $value, 'ParameterValue', $desc)
            }
        }
    }
}
"#;