chrome-cli 1.2.0

A CLI tool for browser automation via the Chrome DevTools Protocol
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
#![allow(clippy::doc_markdown)]
// Items used by the binary crate may appear unused from the library crate's perspective.
#![allow(dead_code)]

use std::path::PathBuf;

use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum};
use clap_complete::Shell;

#[derive(Parser)]
#[command(
    name = "chrome-cli",
    version,
    about = "Browser automation via the Chrome DevTools Protocol",
    long_about = "chrome-cli is a command-line tool for browser automation via the Chrome DevTools \
        Protocol (CDP). It provides subcommands for connecting to Chrome/Chromium instances, \
        managing tabs, navigating pages, inspecting the DOM, executing JavaScript, monitoring \
        console output, intercepting network requests, simulating user interactions, filling forms, \
        emulating devices, and collecting performance metrics.\n\n\
        Designed for AI agents and shell scripting, every subcommand produces structured JSON \
        output on stdout and structured JSON errors on stderr. Global flags control connection \
        settings, output format, and target tab selection.",
    after_long_help = "\
QUICK START:
  # Connect to a running Chrome instance
  chrome-cli connect

  # Launch a new headless Chrome and connect
  chrome-cli connect --launch --headless

  # List open tabs and navigate to a URL
  chrome-cli tabs list
  chrome-cli navigate https://example.com

  # Take a full-page screenshot
  chrome-cli page screenshot --full-page --file shot.png

  # Execute JavaScript and get the result
  chrome-cli js exec \"document.title\"

  # Capture the accessibility tree and fill a form field
  chrome-cli page snapshot
  chrome-cli form fill s5 \"hello@example.com\"

  # Monitor console output in real time
  chrome-cli console follow --timeout 5000

EXIT CODES:
  0  Success
  1  General error (invalid arguments, internal failure)
  2  Connection error (Chrome not running, session expired)
  3  Target error (tab not found, no page targets)
  4  Timeout error (navigation or trace timeout)
  5  Protocol error (CDP protocol failure, dialog handling error)

ENVIRONMENT VARIABLES:
  CHROME_CLI_PORT     CDP port number (default: 9222)
  CHROME_CLI_HOST     CDP host address (default: 127.0.0.1)
  CHROME_CLI_TIMEOUT  Default command timeout in milliseconds
  CHROME_CLI_CONFIG   Path to configuration file",
    term_width = 100
)]
pub struct Cli {
    #[command(flatten)]
    pub global: GlobalOpts,

    #[command(subcommand)]
    pub command: Command,
}

#[derive(Args)]
pub struct GlobalOpts {
    /// Chrome DevTools Protocol port number [default: 9222]
    #[arg(long, global = true, env = "CHROME_CLI_PORT")]
    pub port: Option<u16>,

    /// Chrome DevTools Protocol host address
    #[arg(
        long,
        default_value = "127.0.0.1",
        global = true,
        env = "CHROME_CLI_HOST"
    )]
    pub host: String,

    /// Direct WebSocket URL (overrides --host and --port)
    #[arg(long, global = true)]
    pub ws_url: Option<String>,

    /// Command timeout in milliseconds
    #[arg(long, global = true, env = "CHROME_CLI_TIMEOUT")]
    pub timeout: Option<u64>,

    /// Target tab ID (defaults to the active tab)
    #[arg(long, global = true)]
    pub tab: Option<String>,

    /// Automatically dismiss any dialogs that appear during command execution
    #[arg(long, global = true)]
    pub auto_dismiss_dialogs: bool,

    /// Path to configuration file (overrides default search)
    #[arg(long, global = true, env = "CHROME_CLI_CONFIG")]
    pub config: Option<PathBuf>,

    #[command(flatten)]
    pub output: OutputFormat,
}

impl GlobalOpts {
    /// Returns the port if explicitly provided, or the default (9222).
    /// Default CDP port when none is explicitly provided.
    const DEFAULT_PORT: u16 = 9222;

    #[must_use]
    pub fn port_or_default(&self) -> u16 {
        self.port.unwrap_or(Self::DEFAULT_PORT)
    }
}

#[allow(clippy::struct_excessive_bools)]
#[derive(Args)]
#[group(multiple = false)]
pub struct OutputFormat {
    /// Output as compact JSON (mutually exclusive with --pretty, --plain)
    #[arg(long, global = true)]
    pub json: bool,

    /// Output as pretty-printed JSON (mutually exclusive with --json, --plain)
    #[arg(long, global = true)]
    pub pretty: bool,

    /// Output as human-readable plain text (mutually exclusive with --json, --pretty)
    #[arg(long, global = true)]
    pub plain: bool,
}

#[derive(Subcommand)]
pub enum Command {
    /// Connect to or launch a Chrome instance
    #[command(
        long_about = "Connect to a running Chrome/Chromium instance via the Chrome DevTools \
            Protocol, or launch a new one. Tests the connection and prints browser metadata \
            (browser version, WebSocket URL, user agent). The session is persisted to a \
            local file so subsequent commands reuse the same connection.",
        after_long_help = "\
EXAMPLES:
  # Connect to Chrome on the default port (9222)
  chrome-cli connect

  # Launch a new headless Chrome instance
  chrome-cli connect --launch --headless

  # Connect to a specific port
  chrome-cli connect --port 9333

  # Check connection status
  chrome-cli connect --status

  # Disconnect and remove session file
  chrome-cli connect --disconnect"
    )]
    Connect(ConnectArgs),

    /// Tab management (list, create, close, activate)
    #[command(
        long_about = "Tab management commands: list open tabs, create new tabs, close tabs, and \
            activate (focus) a specific tab. Each operation returns structured JSON with tab IDs \
            and metadata.",
        after_long_help = "\
EXAMPLES:
  # List all open tabs
  chrome-cli tabs list

  # Open a new tab and get its ID
  chrome-cli tabs create https://example.com

  # Close tabs by ID
  chrome-cli tabs close ABC123 DEF456

  # Activate a specific tab
  chrome-cli tabs activate ABC123"
    )]
    Tabs(TabsArgs),

    /// URL navigation and history
    #[command(
        long_about = "Navigate to URLs, reload pages, go back/forward in history, and wait for \
            navigation events. Supports waiting for load, DOMContentLoaded, or network idle.",
        after_long_help = "\
EXAMPLES:
  # Navigate to a URL and wait for page load
  chrome-cli navigate https://example.com

  # Navigate and wait for network idle
  chrome-cli navigate https://example.com --wait-until networkidle

  # Go back in browser history
  chrome-cli navigate back

  # Reload the current page, bypassing cache
  chrome-cli navigate reload --ignore-cache"
    )]
    Navigate(NavigateArgs),

    /// Page inspection (screenshot, text, accessibility tree, find)
    #[command(
        long_about = "Inspect the current page: capture screenshots (full page or element), \
            extract visible text, dump the accessibility tree, or search for text/elements on \
            the page.",
        after_long_help = "\
EXAMPLES:
  # Extract all visible text from the page
  chrome-cli page text

  # Capture the accessibility tree (assigns UIDs to elements)
  chrome-cli page snapshot

  # Take a full-page screenshot
  chrome-cli page screenshot --full-page --file page.png

  # Find elements by text
  chrome-cli page find \"Sign in\"

  # Resize the viewport
  chrome-cli page resize 1280x720"
    )]
    Page(PageArgs),

    /// DOM inspection and manipulation
    #[command(
        long_about = "Query and manipulate the DOM: select elements by CSS selector or XPath, \
            get/set attributes and text, read outerHTML, inspect computed styles, navigate the \
            element tree, and remove elements. Target elements by node ID (from 'dom select'), \
            snapshot UID (from 'page snapshot'), or CSS selector (prefixed with 'css:').",
        after_long_help = "\
EXAMPLES:
  # Select elements by CSS selector
  chrome-cli dom select \"h1\"

  # Select by XPath
  chrome-cli dom select \"//a[@href]\" --xpath

  # Get an element's attribute
  chrome-cli dom get-attribute s3 href

  # Read element text
  chrome-cli dom get-text css:h1

  # Set an attribute
  chrome-cli dom set-attribute s5 class \"highlight\"

  # View the DOM tree
  chrome-cli dom tree --depth 3"
    )]
    Dom(DomArgs),

    /// JavaScript execution in page context
    #[command(
        long_about = "Execute JavaScript expressions or scripts in the page context. Returns \
            the result as structured JSON. Supports both synchronous expressions and async \
            functions.",
        after_long_help = "\
EXAMPLES:
  # Get the page title
  chrome-cli js exec \"document.title\"

  # Execute a script file
  chrome-cli js exec --file script.js

  # Run code on a specific element (by UID from snapshot)
  chrome-cli js exec --uid s3 \"(el) => el.textContent\"

  # Read from stdin
  echo 'document.URL' | chrome-cli js exec -"
    )]
    Js(JsArgs),

    /// Console message reading and monitoring
    #[command(
        long_about = "Read and monitor browser console messages (log, warn, error, info). \
            Can capture existing messages or stream new messages in real time.",
        after_long_help = "\
EXAMPLES:
  # Read recent console messages
  chrome-cli console read

  # Show only error messages
  chrome-cli console read --errors-only

  # Stream console messages in real time
  chrome-cli console follow

  # Stream errors for 10 seconds
  chrome-cli console follow --errors-only --timeout 10000"
    )]
    Console(ConsoleArgs),

    /// Network request monitoring and interception
    #[command(
        long_about = "Monitor and intercept network requests. List recent requests, filter by \
            URL pattern or resource type, capture request/response bodies, and stream requests \
            in real time.",
        after_long_help = "\
EXAMPLES:
  # List recent network requests
  chrome-cli network list

  # Filter by resource type
  chrome-cli network list --type xhr,fetch

  # Get details of a specific request
  chrome-cli network get 42

  # Stream network requests in real time
  chrome-cli network follow --url api.example.com"
    )]
    Network(NetworkArgs),

    /// Mouse, keyboard, and scroll interactions
    #[command(
        long_about = "Simulate user interactions: click elements, type text, press key \
            combinations, scroll the page, hover over elements, and perform drag-and-drop \
            operations. Target elements by UID (from 'page snapshot') or CSS selector \
            (prefixed with 'css:').",
        after_long_help = "\
EXAMPLES:
  # Click an element by UID
  chrome-cli interact click s5

  # Click by CSS selector
  chrome-cli interact click css:#submit-btn

  # Type text into the focused element
  chrome-cli interact type \"Hello, world!\"

  # Press a key combination
  chrome-cli interact key Control+A

  # Scroll down one viewport height
  chrome-cli interact scroll"
    )]
    Interact(InteractArgs),

    /// Form input and submission
    #[command(
        long_about = "Fill in form fields, select dropdown options, toggle checkboxes, and clear \
            fields. Supports targeting fields by UID (from accessibility snapshot) or CSS \
            selector (prefixed with 'css:'). Run 'page snapshot' first to discover field UIDs.",
        after_long_help = "\
EXAMPLES:
  # Fill a field by UID (from page snapshot)
  chrome-cli form fill s5 \"hello@example.com\"

  # Fill by CSS selector
  chrome-cli form fill css:#email \"user@example.com\"

  # Fill multiple fields at once
  chrome-cli form fill-many '[{\"uid\":\"s5\",\"value\":\"Alice\"},{\"uid\":\"s7\",\"value\":\"alice@example.com\"}]'

  # Clear a field
  chrome-cli form clear s5

  # Upload a file
  chrome-cli form upload s10 ./photo.jpg"
    )]
    Form(FormArgs),

    /// Device and network emulation
    #[command(
        long_about = "Emulate different devices, screen sizes, and network conditions. Set \
            custom user agents, viewport dimensions, device scale factor, and network throttling \
            profiles.",
        after_long_help = "\
EXAMPLES:
  # Emulate a mobile device
  chrome-cli emulate set --viewport 375x667 --device-scale 2 --mobile

  # Simulate slow 3G network
  chrome-cli emulate set --network 3g

  # Force dark mode
  chrome-cli emulate set --color-scheme dark

  # Check current emulation settings
  chrome-cli emulate status

  # Clear all emulation overrides
  chrome-cli emulate reset"
    )]
    Emulate(EmulateArgs),

    /// Performance tracing and metrics
    #[command(
        long_about = "Collect performance metrics, capture trace files, measure page load timing, \
            and analyze runtime performance. Outputs metrics as structured JSON for analysis.",
        after_long_help = "\
EXAMPLES:
  # Quick Core Web Vitals measurement
  chrome-cli perf vitals

  # Record a trace until Ctrl+C
  chrome-cli perf record

  # Record a trace for 5 seconds
  chrome-cli perf record --duration 5000

  # Record with page reload
  chrome-cli perf record --reload --duration 5000

  # Analyze a trace for render-blocking resources
  chrome-cli perf analyze RenderBlocking --trace-file trace.json"
    )]
    Perf(PerfArgs),

    /// Browser dialog handling (alert, confirm, prompt, beforeunload)
    #[command(
        long_about = "Detect and handle browser JavaScript dialogs (alert, confirm, prompt, \
            beforeunload). Query whether a dialog is open, accept or dismiss it, and provide \
            prompt text. Useful for automation scripts that need to respond to dialogs \
            programmatically.",
        after_long_help = "\
EXAMPLES:
  # Check if a dialog is open
  chrome-cli dialog info

  # Accept an alert or confirm dialog
  chrome-cli dialog handle accept

  # Dismiss a dialog
  chrome-cli dialog handle dismiss

  # Accept a prompt with text
  chrome-cli dialog handle accept --text \"my input\""
    )]
    Dialog(DialogArgs),

    /// Configuration file management (show, init, path)
    #[command(
        long_about = "Manage the chrome-cli configuration file. Show the resolved configuration \
            from all sources, create a default config file, or display the active config file path. \
            Config files use TOML format and are searched in priority order: --config flag, \
            $CHROME_CLI_CONFIG env var, project-local, XDG config dir, home directory.",
        after_long_help = "\
EXAMPLES:
  # Show the resolved configuration
  chrome-cli config show

  # Create a default config file
  chrome-cli config init

  # Create a config at a custom path
  chrome-cli config init --path ./my-config.toml

  # Show the active config file path
  chrome-cli config path"
    )]
    Config(ConfigArgs),

    /// Generate shell completion scripts
    #[command(
        long_about = "Generate shell completion scripts for tab-completion of commands, flags, \
            and enum values. Pipe the output to the appropriate file for your shell.",
        after_long_help = "\
EXAMPLES:
  # Bash
  chrome-cli completions bash > /etc/bash_completion.d/chrome-cli

  # Zsh
  chrome-cli completions zsh > ~/.zfunc/_chrome-cli

  # Fish
  chrome-cli completions fish > ~/.config/fish/completions/chrome-cli.fish

  # PowerShell
  chrome-cli completions powershell >> $PROFILE

  # Elvish
  chrome-cli completions elvish >> ~/.elvish/rc.elv"
    )]
    Completions(CompletionsArgs),

    /// Show usage examples for commands
    #[command(
        long_about = "Show usage examples for chrome-cli commands. Without arguments, lists all \
            command groups with a brief description and one example each. With a command name, \
            shows detailed examples for that specific command group.",
        after_long_help = "\
EXAMPLES:
  # List all command groups with summary examples
  chrome-cli examples

  # Show detailed examples for the navigate command
  chrome-cli examples navigate

  # Get all examples as JSON (for programmatic use)
  chrome-cli examples --json

  # Pretty-printed JSON output
  chrome-cli examples --pretty"
    )]
    Examples(ExamplesArgs),

    /// Output a machine-readable manifest of all CLI capabilities
    #[command(
        long_about = "Output a complete, machine-readable JSON manifest describing every command, \
            subcommand, flag, argument, and type in the CLI. Designed for AI agents and tooling \
            that need to programmatically discover the CLI surface. The manifest is generated at \
            runtime from the clap command tree, so it is always in sync with the binary.",
        after_long_help = "\
EXAMPLES:
  # Full capabilities manifest
  chrome-cli capabilities

  # Pretty-printed for readability
  chrome-cli capabilities --pretty

  # Capabilities for a specific command
  chrome-cli capabilities --command navigate

  # Compact listing (names and descriptions only)
  chrome-cli capabilities --compact"
    )]
    Capabilities(CapabilitiesArgs),

    /// Display man pages for chrome-cli commands
    #[command(
        long_about = "Display man pages for chrome-cli commands. Without arguments, displays \
            the main chrome-cli man page. With a subcommand name, displays the man page for \
            that specific command. Output is in roff format, suitable for piping to a pager.",
        after_long_help = "\
EXAMPLES:
  # Display the main chrome-cli man page
  chrome-cli man

  # Display the man page for the connect command
  chrome-cli man connect

  # Display the man page for the tabs command
  chrome-cli man tabs

  # Pipe to a pager
  chrome-cli man navigate | less"
    )]
    Man(ManArgs),
}

/// Chrome release channel to use when launching.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ChromeChannel {
    Stable,
    Canary,
    Beta,
    Dev,
}

/// Arguments for the `tabs` subcommand group.
#[derive(Args)]
pub struct TabsArgs {
    #[command(subcommand)]
    pub command: TabsCommand,
}

/// Tab management subcommands.
#[derive(Subcommand)]
pub enum TabsCommand {
    /// List open tabs
    #[command(
        long_about = "List all open browser tabs. Returns JSON with each tab's ID, title, URL, \
            and type. By default, only page tabs are shown; use --all to include internal \
            Chrome pages (chrome://, chrome-extension://).",
        after_long_help = "\
EXAMPLES:
  # List page tabs
  chrome-cli tabs list

  # Include internal Chrome pages
  chrome-cli tabs list --all"
    )]
    List(TabsListArgs),

    /// Create a new tab
    #[command(
        long_about = "Create a new browser tab. Optionally specify a URL to open; defaults to \
            about:blank. Returns JSON with the new tab's ID and URL. Use --background to open \
            the tab without switching focus to it.",
        after_long_help = "\
EXAMPLES:
  # Open a blank tab
  chrome-cli tabs create

  # Open a URL
  chrome-cli tabs create https://example.com

  # Open in the background
  chrome-cli tabs create https://example.com --background"
    )]
    Create(TabsCreateArgs),

    /// Close one or more tabs
    #[command(
        long_about = "Close one or more browser tabs by their IDs. Accepts multiple tab IDs \
            as arguments. Returns JSON confirming which tabs were closed. Cannot close the \
            last remaining tab (Chrome requires at least one open tab).",
        after_long_help = "\
EXAMPLES:
  # Close a single tab
  chrome-cli tabs close ABC123

  # Close multiple tabs
  chrome-cli tabs close ABC123 DEF456 GHI789"
    )]
    Close(TabsCloseArgs),

    /// Activate (focus) a tab
    #[command(
        long_about = "Activate (bring to front) a specific browser tab by its ID. The tab \
            becomes the active target for subsequent commands. Returns JSON confirming the \
            activated tab.",
        after_long_help = "\
EXAMPLES:
  # Activate a tab by ID
  chrome-cli tabs activate ABC123

  # Activate silently
  chrome-cli tabs activate ABC123 --quiet"
    )]
    Activate(TabsActivateArgs),
}

/// Arguments for `tabs list`.
#[derive(Args)]
pub struct TabsListArgs {
    /// Include internal Chrome pages (chrome://, chrome-extension://)
    #[arg(long)]
    pub all: bool,
}

/// Arguments for `tabs create`.
#[derive(Args)]
pub struct TabsCreateArgs {
    /// URL to open (defaults to about:blank)
    pub url: Option<String>,

    /// Open the tab in the background without activating it
    #[arg(long)]
    pub background: bool,
}

/// Arguments for `tabs close`.
#[derive(Args)]
pub struct TabsCloseArgs {
    /// Tab ID(s) or index(es) to close
    #[arg(required = true)]
    pub targets: Vec<String>,
}

/// Arguments for `tabs activate`.
#[derive(Args)]
pub struct TabsActivateArgs {
    /// Tab ID or index to activate
    pub target: String,

    /// Suppress output after activation
    #[arg(long)]
    pub quiet: bool,
}

/// Arguments for the `navigate` subcommand group.
#[derive(Args)]
#[command(args_conflicts_with_subcommands = true)]
pub struct NavigateArgs {
    #[command(subcommand)]
    pub command: Option<NavigateCommand>,

    #[command(flatten)]
    pub url_args: NavigateUrlArgs,
}

/// Navigate subcommands.
#[derive(Subcommand)]
pub enum NavigateCommand {
    /// Go back in browser history
    #[command(
        long_about = "Navigate back one step in the browser's session history, equivalent to \
            clicking the browser's back button. Returns JSON with the new URL after navigation.",
        after_long_help = "\
EXAMPLES:
  # Go back
  chrome-cli navigate back"
    )]
    Back,

    /// Go forward in browser history
    #[command(
        long_about = "Navigate forward one step in the browser's session history, equivalent to \
            clicking the browser's forward button. Only works if the user previously navigated \
            back. Returns JSON with the new URL after navigation.",
        after_long_help = "\
EXAMPLES:
  # Go forward
  chrome-cli navigate forward"
    )]
    Forward,

    /// Reload the current page
    #[command(
        long_about = "Reload the current page. Use --ignore-cache to bypass the browser cache \
            and force a full reload from the server. Returns JSON with the page URL after reload.",
        after_long_help = "\
EXAMPLES:
  # Reload the page
  chrome-cli navigate reload

  # Reload bypassing cache
  chrome-cli navigate reload --ignore-cache"
    )]
    Reload(NavigateReloadArgs),
}

/// Arguments for direct URL navigation (`navigate <URL>`).
#[derive(Args)]
pub struct NavigateUrlArgs {
    /// URL to navigate to
    pub url: Option<String>,

    /// Wait strategy after navigation
    #[arg(long, value_enum, default_value_t = WaitUntil::Load)]
    pub wait_until: WaitUntil,

    /// Navigation timeout in milliseconds
    #[arg(long)]
    pub timeout: Option<u64>,

    /// Bypass the browser cache
    #[arg(long)]
    pub ignore_cache: bool,
}

/// Arguments for `navigate reload`.
#[derive(Args)]
pub struct NavigateReloadArgs {
    /// Bypass the browser cache on reload
    #[arg(long)]
    pub ignore_cache: bool,
}

/// Arguments for the `page` subcommand group.
#[derive(Args)]
pub struct PageArgs {
    #[command(subcommand)]
    pub command: PageCommand,
}

/// Page inspection subcommands.
#[derive(Subcommand)]
pub enum PageCommand {
    /// Extract visible text from the page
    #[command(
        long_about = "Extract the visible text content from the current page or a specific \
            element. Returns the text as a plain string. Useful for reading page content \
            without HTML markup.",
        after_long_help = "\
EXAMPLES:
  # Get all visible text
  chrome-cli page text

  # Get text from a specific element
  chrome-cli page text --selector \"#main-content\""
    )]
    Text(PageTextArgs),

    /// Capture the accessibility tree of the page
    #[command(
        long_about = "Capture the accessibility tree (AX tree) of the current page. Each \
            interactive element is assigned a UID (e.g., s1, s2, s3) that can be used with \
            'interact', 'form', and 'js exec --uid' commands. Use --verbose to include \
            additional properties like checked, disabled, and level.",
        after_long_help = "\
EXAMPLES:
  # Capture the accessibility tree
  chrome-cli page snapshot

  # Verbose output with extra properties
  chrome-cli page snapshot --verbose

  # Save to a file
  chrome-cli page snapshot --file snapshot.txt"
    )]
    Snapshot(PageSnapshotArgs),

    /// Find elements by text, CSS selector, or accessibility role
    #[command(
        long_about = "Search for elements on the page by text content, CSS selector, or \
            accessibility role. Returns matching elements with their UIDs, roles, and names. \
            By default, performs a case-insensitive substring match; use --exact for exact \
            matching.",
        after_long_help = "\
EXAMPLES:
  # Find elements by text
  chrome-cli page find \"Sign in\"

  # Find by CSS selector
  chrome-cli page find --selector \"button.primary\"

  # Find by accessibility role
  chrome-cli page find --role button

  # Exact text match with limit
  chrome-cli page find \"Submit\" --exact --limit 1"
    )]
    Find(PageFindArgs),

    /// Capture a screenshot of the page, an element, or a region
    #[command(
        long_about = "Capture a screenshot of the current page, a specific element, or a \
            viewport region. Supports PNG (default), JPEG, and WebP formats. Use --full-page \
            to capture the entire scrollable page, --selector or --uid to capture a specific \
            element, or --clip to capture a region. Note: --full-page conflicts with \
            --selector, --uid, and --clip.",
        after_long_help = "\
EXAMPLES:
  # Screenshot the visible viewport
  chrome-cli page screenshot --file shot.png

  # Full-page screenshot
  chrome-cli page screenshot --full-page --file full.png

  # Screenshot a specific element by UID
  chrome-cli page screenshot --uid s3 --file element.png

  # JPEG format with quality
  chrome-cli page screenshot --format jpeg --quality 80 --file shot.jpg"
    )]
    Screenshot(PageScreenshotArgs),

    /// Resize the viewport to the given dimensions
    #[command(
        long_about = "Resize the browser viewport to the specified dimensions. The size is \
            given as WIDTHxHEIGHT in pixels (e.g., 1280x720). Useful for testing responsive \
            layouts. See also: 'emulate set --viewport' for device emulation.",
        after_long_help = "\
EXAMPLES:
  # Resize to 1280x720
  chrome-cli page resize 1280x720

  # Mobile viewport
  chrome-cli page resize 375x667"
    )]
    Resize(PageResizeArgs),
}

/// Image format for screenshots.
#[derive(Debug, Clone, Copy, ValueEnum, Default)]
pub enum ScreenshotFormat {
    /// PNG (lossless, default)
    #[default]
    Png,
    /// JPEG (lossy)
    Jpeg,
    /// WebP (lossy)
    Webp,
}

/// Arguments for `page screenshot`.
#[derive(Args)]
pub struct PageScreenshotArgs {
    /// Capture the entire scrollable page, not just the visible viewport
    #[arg(long)]
    pub full_page: bool,

    /// Capture a specific element by CSS selector (conflicts with --full-page)
    #[arg(long)]
    pub selector: Option<String>,

    /// Capture a specific element by UID from 'page snapshot' (conflicts with --full-page)
    #[arg(long)]
    pub uid: Option<String>,

    /// Image format [default: png] [possible values: png, jpeg, webp]
    #[arg(long, value_enum, default_value_t = ScreenshotFormat::Png)]
    pub format: ScreenshotFormat,

    /// JPEG/WebP compression quality, 0-100 (ignored for PNG)
    #[arg(long, value_parser = clap::value_parser!(u8).range(0..=100))]
    pub quality: Option<u8>,

    /// Save screenshot to a file instead of base64-encoded stdout
    #[arg(long)]
    pub file: Option<PathBuf>,

    /// Capture a specific viewport region as X,Y,WIDTH,HEIGHT (e.g. 10,20,200,100)
    #[arg(long)]
    pub clip: Option<String>,
}

/// Arguments for `page text`.
#[derive(Args)]
pub struct PageTextArgs {
    /// CSS selector to extract text from a specific element
    #[arg(long)]
    pub selector: Option<String>,
}

/// Arguments for `page snapshot`.
#[derive(Args)]
pub struct PageSnapshotArgs {
    /// Include additional element properties (checked, disabled, level, etc.)
    #[arg(long)]
    pub verbose: bool,

    /// Save snapshot to file instead of stdout
    #[arg(long)]
    pub file: Option<PathBuf>,
}

/// Arguments for `page find`.
#[derive(Args)]
pub struct PageFindArgs {
    /// Text to search for (searches accessible names, text content, labels)
    pub query: Option<String>,

    /// Find by CSS selector instead of text
    #[arg(long)]
    pub selector: Option<String>,

    /// Filter by accessibility role (button, link, textbox, etc.)
    #[arg(long)]
    pub role: Option<String>,

    /// Require exact text match (default: case-insensitive substring)
    #[arg(long)]
    pub exact: bool,

    /// Maximum results to return
    #[arg(long, default_value_t = 10)]
    pub limit: usize,
}

/// Arguments for the `perf` subcommand group.
#[derive(Args)]
pub struct PerfArgs {
    #[command(subcommand)]
    pub command: PerfCommand,
}

/// Performance tracing subcommands.
#[derive(Subcommand)]
pub enum PerfCommand {
    /// Record a performance trace (long-running, stops on Ctrl+C or --duration)
    #[command(
        long_about = "Record a performance trace in a single long-running session. The trace \
            captures JavaScript execution, layout, paint, network, and other browser activity. \
            Recording continues until you press Ctrl+C or the --duration timeout elapses. \
            Use --reload to reload the page before recording. The trace is saved to a JSON \
            file that can be opened in Chrome DevTools or analyzed with 'perf analyze'.",
        after_long_help = "\
EXAMPLES:
  # Record until Ctrl+C
  chrome-cli perf record

  # Record for 5 seconds
  chrome-cli perf record --duration 5000

  # Record with page reload
  chrome-cli perf record --reload --duration 5000

  # Save to a specific file
  chrome-cli perf record --file my-trace.json"
    )]
    Record(PerfRecordArgs),

    /// Analyze a specific performance insight from a trace
    #[command(
        long_about = "Analyze a previously saved trace file for a specific performance insight. \
            Available insights: DocumentLatency (document request timing), LCPBreakdown (Largest \
            Contentful Paint phases), RenderBlocking (render-blocking resources), LongTasks \
            (JavaScript tasks > 50ms). Returns structured JSON with the analysis results.",
        after_long_help = "\
EXAMPLES:
  # Analyze LCP breakdown
  chrome-cli perf analyze LCPBreakdown --trace-file trace.json

  # Find render-blocking resources
  chrome-cli perf analyze RenderBlocking --trace-file trace.json

  # Identify long tasks
  chrome-cli perf analyze LongTasks --trace-file trace.json"
    )]
    Analyze(PerfAnalyzeArgs),

    /// Quick Core Web Vitals measurement
    #[command(
        long_about = "Perform a quick Core Web Vitals measurement. Automatically starts a \
            trace, reloads the page, collects vitals (LCP, FID, CLS), and stops the trace. \
            Returns structured JSON with the web vitals metrics.",
        after_long_help = "\
EXAMPLES:
  # Measure web vitals
  chrome-cli perf vitals

  # Save the underlying trace file
  chrome-cli perf vitals --file vitals-trace.json"
    )]
    Vitals(PerfVitalsArgs),
}

/// Arguments for `perf record`.
#[derive(Args)]
pub struct PerfRecordArgs {
    /// Reload the page before recording
    #[arg(long)]
    pub reload: bool,
    /// Auto-stop after this many milliseconds
    #[arg(long)]
    pub duration: Option<u64>,
    /// Path to save the trace file (default: auto-generated)
    #[arg(long)]
    pub file: Option<PathBuf>,
}

/// Arguments for `perf analyze`.
#[derive(Args)]
pub struct PerfAnalyzeArgs {
    /// Insight to analyze: DocumentLatency, LCPBreakdown, RenderBlocking, LongTasks
    pub insight: String,
    /// Path to a previously saved trace JSON file
    #[arg(long)]
    pub trace_file: PathBuf,
}

/// Arguments for `perf vitals`.
#[derive(Args)]
pub struct PerfVitalsArgs {
    /// Path to save the trace file (default: auto-generated temp)
    #[arg(long)]
    pub file: Option<PathBuf>,
}

/// Arguments for the `js` subcommand group.
#[derive(Args)]
pub struct JsArgs {
    #[command(subcommand)]
    pub command: JsCommand,
}

/// JavaScript subcommands.
#[derive(Subcommand)]
pub enum JsCommand {
    /// Execute JavaScript in the page context
    #[command(
        long_about = "Execute a JavaScript expression or script in the page context and return \
            the result as JSON. Code can be provided as an inline argument, read from a file \
            with --file, or piped via stdin using '-'. When --uid is specified, the code is \
            wrapped in a function that receives the element as its first argument. By default, \
            promise results are awaited; use --no-await to return immediately.",
        after_long_help = "\
EXAMPLES:
  # Evaluate an expression
  chrome-cli js exec \"document.title\"

  # Execute a script file
  chrome-cli js exec --file script.js

  # Run code on a specific element
  chrome-cli js exec --uid s3 \"(el) => el.textContent\"

  # Read from stdin
  echo 'document.URL' | chrome-cli js exec -

  # Skip awaiting promises
  chrome-cli js exec --no-await \"fetch('/api/data')\""
    )]
    Exec(JsExecArgs),
}

/// Arguments for `js exec`.
#[derive(Args)]
pub struct JsExecArgs {
    /// JavaScript code to execute (use '-' to read from stdin; conflicts with --file)
    #[arg(conflicts_with = "file")]
    pub code: Option<String>,

    /// Read JavaScript from a file instead of inline argument (conflicts with CODE)
    #[arg(long)]
    pub file: Option<PathBuf>,

    /// Element UID from 'page snapshot'; code is wrapped in a function receiving the element
    #[arg(long)]
    pub uid: Option<String>,

    /// Return promise objects without awaiting them
    #[arg(long, action = ArgAction::SetTrue)]
    pub no_await: bool,

    /// Execution timeout in milliseconds (overrides global --timeout)
    #[arg(long)]
    pub timeout: Option<u64>,

    /// Truncate result output exceeding this size in bytes
    #[arg(long)]
    pub max_size: Option<usize>,
}

/// Arguments for the `dialog` subcommand group.
#[derive(Args)]
pub struct DialogArgs {
    #[command(subcommand)]
    pub command: DialogCommand,
}

/// Dialog subcommands.
#[derive(Subcommand)]
pub enum DialogCommand {
    /// Accept or dismiss the current browser dialog
    #[command(
        long_about = "Accept or dismiss the currently open browser dialog (alert, confirm, \
            prompt, or beforeunload). A dialog must be open before this command can be used. \
            For prompt dialogs, use --text to provide the response text when accepting.",
        after_long_help = "\
EXAMPLES:
  # Accept an alert
  chrome-cli dialog handle accept

  # Dismiss a confirm dialog
  chrome-cli dialog handle dismiss

  # Accept a prompt with text
  chrome-cli dialog handle accept --text \"my response\""
    )]
    Handle(DialogHandleArgs),

    /// Check whether a dialog is currently open
    #[command(
        long_about = "Check whether a JavaScript dialog (alert, confirm, prompt, or \
            beforeunload) is currently open. Returns JSON with the dialog's type, message, \
            and default prompt text if applicable. Returns {\"open\": false} when no dialog \
            is present.",
        after_long_help = "\
EXAMPLES:
  # Check for open dialog
  chrome-cli dialog info"
    )]
    Info,
}

/// Arguments for `dialog handle`.
#[derive(Args)]
pub struct DialogHandleArgs {
    /// Action to take: accept or dismiss
    pub action: DialogAction,

    /// Response text for prompt dialogs (only used with 'accept' action)
    #[arg(long)]
    pub text: Option<String>,
}

/// Action to take on a browser dialog.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum DialogAction {
    /// Accept (OK) the dialog
    Accept,
    /// Dismiss (Cancel) the dialog
    Dismiss,
}

/// Wait strategy for navigation commands.
#[derive(Debug, Clone, Copy, ValueEnum, Default, PartialEq, Eq)]
pub enum WaitUntil {
    /// Wait for the load event
    #[default]
    Load,
    /// Wait for DOMContentLoaded event
    Domcontentloaded,
    /// Wait until network is idle (no requests for 500ms)
    Networkidle,
    /// Return immediately after initiating navigation
    None,
}

/// Arguments for the `connect` subcommand.
#[allow(clippy::struct_excessive_bools)]
#[derive(Args)]
pub struct ConnectArgs {
    /// Launch a new Chrome instance instead of connecting to an existing one
    #[arg(long)]
    pub launch: bool,

    /// Show current connection status (conflicts with --launch, --disconnect)
    #[arg(long, conflicts_with_all = ["launch", "disconnect"])]
    pub status: bool,

    /// Disconnect and remove session file (conflicts with --launch, --status)
    #[arg(long, conflicts_with_all = ["launch", "status"])]
    pub disconnect: bool,

    /// Launch Chrome in headless mode
    #[arg(long, requires = "launch")]
    pub headless: bool,

    /// Chrome release channel to launch [default: stable] [possible values: stable, canary, beta, dev]
    #[arg(long, requires = "launch", default_value = "stable")]
    pub channel: ChromeChannel,

    /// Path to a Chrome/Chromium executable (overrides channel-based discovery)
    #[arg(long, requires = "launch")]
    pub chrome_path: Option<PathBuf>,

    /// Additional arguments to pass to Chrome (can be repeated)
    #[arg(long, requires = "launch")]
    pub chrome_arg: Vec<String>,
}

/// Arguments for the `interact` subcommand group.
#[derive(Args)]
pub struct InteractArgs {
    #[command(subcommand)]
    pub command: InteractCommand,
}

/// Interact subcommands.
#[derive(Subcommand)]
pub enum InteractCommand {
    /// Click an element by UID or CSS selector
    #[command(
        long_about = "Click an element identified by UID (from 'page snapshot', e.g., 's5') or \
            CSS selector (prefixed with 'css:', e.g., 'css:#submit'). By default, performs a \
            left single-click at the element's center. Use --double for double-click or --right \
            for right-click (context menu). These flags are mutually exclusive.",
        after_long_help = "\
EXAMPLES:
  # Click by UID
  chrome-cli interact click s5

  # Click by CSS selector
  chrome-cli interact click css:#submit-btn

  # Double-click
  chrome-cli interact click s5 --double

  # Right-click (context menu)
  chrome-cli interact click s5 --right"
    )]
    Click(ClickArgs),

    /// Click at viewport coordinates
    #[command(
        long_about = "Click at specific viewport coordinates (X, Y in pixels). Useful when \
            targeting elements that are not in the accessibility tree or for precise coordinate-\
            based interactions. Use --double for double-click or --right for right-click.",
        after_long_help = "\
EXAMPLES:
  # Click at coordinates
  chrome-cli interact click-at 100 200

  # Double-click at coordinates
  chrome-cli interact click-at 100 200 --double"
    )]
    ClickAt(ClickAtArgs),

    /// Hover over an element
    #[command(
        long_about = "Move the mouse over an element identified by UID or CSS selector. \
            Triggers hover effects, tooltips, and mouseover events. Does not click.",
        after_long_help = "\
EXAMPLES:
  # Hover by UID
  chrome-cli interact hover s3

  # Hover by CSS selector
  chrome-cli interact hover css:.tooltip-trigger"
    )]
    Hover(HoverArgs),

    /// Drag from one element to another
    #[command(
        long_about = "Drag from one element to another. Both source and target are identified \
            by UID or CSS selector. Simulates mouse down on the source, move to the target, \
            and mouse up on the target.",
        after_long_help = "\
EXAMPLES:
  # Drag between elements by UID
  chrome-cli interact drag s3 s7

  # Drag using CSS selectors
  chrome-cli interact drag css:#item css:#dropzone"
    )]
    Drag(DragArgs),

    /// Type text character-by-character into the focused element
    #[command(
        long_about = "Type text character-by-character into the currently focused element. \
            Simulates individual key press and release events for each character. Use --delay \
            to add a pause between keystrokes. To focus an element first, use 'interact click'.",
        after_long_help = "\
EXAMPLES:
  # Type text
  chrome-cli interact type \"Hello, world!\"

  # Type with delay between keystrokes
  chrome-cli interact type \"slow typing\" --delay 50"
    )]
    Type(TypeArgs),

    /// Press a key or key combination (e.g. Enter, Control+A)
    #[command(
        long_about = "Press a key or key combination. Supports modifier keys (Control, Shift, \
            Alt, Meta) combined with regular keys using '+' separator. Use --repeat to press \
            the key multiple times. Common keys: Enter, Tab, Escape, Backspace, ArrowUp, \
            ArrowDown, ArrowLeft, ArrowRight, Home, End, PageUp, PageDown, Delete.",
        after_long_help = "\
EXAMPLES:
  # Press Enter
  chrome-cli interact key Enter

  # Select all (Ctrl+A)
  chrome-cli interact key Control+A

  # Press Tab 3 times
  chrome-cli interact key Tab --repeat 3

  # Multi-modifier combo
  chrome-cli interact key Control+Shift+ArrowRight"
    )]
    Key(KeyArgs),

    /// Scroll the page or a container element
    #[command(
        long_about = "Scroll the page or a specific container element. By default, scrolls \
            down by one viewport height. Use --direction to scroll in other directions, \
            --amount to set a custom distance in pixels, or the shortcut flags --to-top, \
            --to-bottom, --to-element to scroll to specific positions. Use --container to \
            scroll within a scrollable child element. Use --smooth for animated scrolling.",
        after_long_help = "\
EXAMPLES:
  # Scroll down one viewport height
  chrome-cli interact scroll

  # Scroll up 200 pixels
  chrome-cli interact scroll --direction up --amount 200

  # Scroll to bottom of page
  chrome-cli interact scroll --to-bottom

  # Scroll until an element is visible
  chrome-cli interact scroll --to-element s15

  # Smooth scroll within a container
  chrome-cli interact scroll --container css:.scrollable --smooth"
    )]
    Scroll(ScrollArgs),
}

/// Arguments for `interact click`.
#[derive(Args)]
pub struct ClickArgs {
    /// Target element (UID like 's1' or CSS selector like 'css:#button')
    pub target: String,

    /// Perform a double-click instead of single click (conflicts with --right)
    #[arg(long, conflicts_with = "right")]
    pub double: bool,

    /// Perform a right-click (context menu) instead of left click (conflicts with --double)
    #[arg(long, conflicts_with = "double")]
    pub right: bool,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for `interact click-at`.
#[derive(Args)]
pub struct ClickAtArgs {
    /// X coordinate in viewport pixels
    pub x: f64,

    /// Y coordinate in viewport pixels
    pub y: f64,

    /// Perform a double-click instead of single click (conflicts with --right)
    #[arg(long, conflicts_with = "right")]
    pub double: bool,

    /// Perform a right-click (context menu) instead of left click (conflicts with --double)
    #[arg(long, conflicts_with = "double")]
    pub right: bool,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for `interact hover`.
#[derive(Args)]
pub struct HoverArgs {
    /// Target element (UID like 's1' or CSS selector like 'css:#button')
    pub target: String,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for `interact drag`.
#[derive(Args)]
pub struct DragArgs {
    /// Source element to drag from (UID or CSS selector)
    pub from: String,

    /// Target element to drag to (UID or CSS selector)
    pub to: String,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for `interact type`.
#[derive(Args)]
pub struct TypeArgs {
    /// Text to type character-by-character
    #[arg(required = true)]
    pub text: String,

    /// Delay between keystrokes in milliseconds (default: 0 for instant)
    #[arg(long, default_value_t = 0)]
    pub delay: u64,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for `interact key`.
#[derive(Args)]
pub struct KeyArgs {
    /// Key or key combination to press (e.g. Enter, Control+A, Shift+ArrowDown)
    #[arg(required = true)]
    pub keys: String,

    /// Number of times to press the key
    #[arg(long, default_value_t = 1)]
    pub repeat: u32,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Scroll direction for `interact scroll`.
#[derive(Debug, Clone, Copy, ValueEnum, Default)]
pub enum ScrollDirection {
    /// Scroll down (default)
    #[default]
    Down,
    /// Scroll up
    Up,
    /// Scroll left
    Left,
    /// Scroll right
    Right,
}

/// Arguments for `interact scroll`.
#[allow(clippy::struct_excessive_bools)]
#[derive(Args)]
pub struct ScrollArgs {
    /// Scroll direction
    #[arg(long, value_enum, default_value_t = ScrollDirection::Down,
           conflicts_with_all = ["to_element", "to_top", "to_bottom"])]
    pub direction: ScrollDirection,

    /// Scroll distance in pixels (default: viewport height for vertical, viewport width for horizontal)
    #[arg(long, conflicts_with_all = ["to_element", "to_top", "to_bottom"])]
    pub amount: Option<u32>,

    /// Scroll until a specific element is in view (UID like 's5' or CSS selector like 'css:#footer')
    #[arg(long, conflicts_with_all = ["direction", "amount", "to_top", "to_bottom", "container"])]
    pub to_element: Option<String>,

    /// Scroll to the top of the page
    #[arg(long, conflicts_with_all = ["direction", "amount", "to_element", "to_bottom", "container"])]
    pub to_top: bool,

    /// Scroll to the bottom of the page
    #[arg(long, conflicts_with_all = ["direction", "amount", "to_element", "to_top", "container"])]
    pub to_bottom: bool,

    /// Use smooth scrolling behavior
    #[arg(long)]
    pub smooth: bool,

    /// Scroll within a container element (UID like 's3' or CSS selector like 'css:.scrollable')
    #[arg(long, conflicts_with_all = ["to_element", "to_top", "to_bottom"])]
    pub container: Option<String>,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for the `form` subcommand group.
#[derive(Args)]
pub struct FormArgs {
    #[command(subcommand)]
    pub command: FormCommand,
}

/// Form subcommands.
#[derive(Subcommand)]
pub enum FormCommand {
    /// Fill a form field by UID or CSS selector
    #[command(
        long_about = "Set the value of a form field identified by UID (from 'page snapshot', \
            e.g., 's5') or CSS selector (prefixed with 'css:', e.g., 'css:#email'). Works \
            with text inputs, textareas, select dropdowns, and checkboxes. Dispatches change \
            and input events to trigger form validation.",
        after_long_help = "\
EXAMPLES:
  # Fill by UID
  chrome-cli form fill s5 \"hello@example.com\"

  # Fill by CSS selector
  chrome-cli form fill css:#email \"user@example.com\"

  # Select a dropdown option
  chrome-cli form fill s8 \"Option B\""
    )]
    Fill(FormFillArgs),

    /// Fill multiple form fields at once from JSON
    #[command(
        long_about = "Fill multiple form fields in a single command. Accepts a JSON array of \
            {uid, value} objects either as an inline argument or from a file with --file. Each \
            field is filled in order. Useful for completing entire forms in one step.",
        after_long_help = "\
EXAMPLES:
  # Fill multiple fields inline
  chrome-cli form fill-many '[{\"uid\":\"s5\",\"value\":\"Alice\"},{\"uid\":\"s7\",\"value\":\"alice@example.com\"}]'

  # Fill from a JSON file
  chrome-cli form fill-many --file form-data.json"
    )]
    FillMany(FormFillManyArgs),

    /// Clear a form field's value
    #[command(
        long_about = "Clear the value of a form field identified by UID or CSS selector. \
            Sets the field to an empty string and dispatches change and input events.",
        after_long_help = "\
EXAMPLES:
  # Clear a field by UID
  chrome-cli form clear s5

  # Clear by CSS selector
  chrome-cli form clear css:#search-input"
    )]
    Clear(FormClearArgs),

    /// Upload files to a file input element
    #[command(
        long_about = "Upload one or more files to a file input element identified by UID or \
            CSS selector. The element must be an <input type=\"file\">. Multiple file paths \
            can be specified for multi-file upload inputs.",
        after_long_help = "\
EXAMPLES:
  # Upload a single file
  chrome-cli form upload s10 ./photo.jpg

  # Upload multiple files
  chrome-cli form upload css:#file-input ./doc1.pdf ./doc2.pdf"
    )]
    Upload(FormUploadArgs),
}

/// Arguments for `form fill`.
#[derive(Args)]
pub struct FormFillArgs {
    /// Target element (UID like 's1' or CSS selector like 'css:#email')
    pub target: String,

    /// Value to set on the form field
    pub value: String,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for `form fill-many`.
#[derive(Args)]
pub struct FormFillManyArgs {
    /// Inline JSON array of {uid, value} objects
    #[arg(value_name = "JSON")]
    pub input: Option<String>,

    /// Read JSON from a file instead of inline argument
    #[arg(long)]
    pub file: Option<PathBuf>,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for `form clear`.
#[derive(Args)]
pub struct FormClearArgs {
    /// Target element (UID like 's1' or CSS selector like 'css:#email')
    pub target: String,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for `form upload`.
#[derive(Args)]
pub struct FormUploadArgs {
    /// Target file input element (UID like 's5' or CSS selector like 'css:#file-input')
    pub target: String,

    /// File paths to upload
    #[arg(required = true)]
    pub files: Vec<PathBuf>,

    /// Include updated accessibility snapshot in output
    #[arg(long)]
    pub include_snapshot: bool,
}

/// Arguments for the `console` subcommand group.
#[derive(Args)]
pub struct ConsoleArgs {
    #[command(subcommand)]
    pub command: ConsoleCommand,
}

/// Console subcommands.
#[derive(Subcommand)]
pub enum ConsoleCommand {
    /// List console messages or get details of a specific message
    #[command(
        long_about = "Read captured console messages from the current page. Without arguments, \
            lists recent messages with their IDs, types, and text. Pass a message ID to get \
            full details including stack trace and arguments. Filter by type or use --errors-only \
            for error and assert messages only.",
        after_long_help = "\
EXAMPLES:
  # List recent console messages
  chrome-cli console read

  # Get details of a specific message
  chrome-cli console read 42

  # Show only errors
  chrome-cli console read --errors-only

  # Filter by type
  chrome-cli console read --type warn,error --limit 20"
    )]
    Read(ConsoleReadArgs),

    /// Stream console messages in real-time (tail -f style)
    #[command(
        long_about = "Stream new console messages in real time as they are logged, similar to \
            'tail -f'. Each message is printed as a JSON line. Use --timeout to auto-exit \
            after a specified duration. Filter by type or use --errors-only to stream only \
            error and assert messages.",
        after_long_help = "\
EXAMPLES:
  # Stream all console output
  chrome-cli console follow

  # Stream errors only for 10 seconds
  chrome-cli console follow --errors-only --timeout 10000

  # Stream specific message types
  chrome-cli console follow --type log,warn"
    )]
    Follow(ConsoleFollowArgs),
}

/// Arguments for `console read`.
#[derive(Args)]
pub struct ConsoleReadArgs {
    /// Message ID to get detailed information about a specific message
    pub msg_id: Option<u64>,

    /// Filter by message type (comma-separated: log,error,warn,info,debug,dir,table,trace,assert,count,timeEnd)
    #[arg(long, value_name = "TYPES", conflicts_with = "errors_only")]
    pub r#type: Option<String>,

    /// Show only error and assert messages (shorthand for --type error,assert)
    #[arg(long, conflicts_with = "type")]
    pub errors_only: bool,

    /// Maximum number of messages to return
    #[arg(long, default_value_t = 50)]
    pub limit: usize,

    /// Pagination page number (0-based)
    #[arg(long, default_value_t = 0)]
    pub page: usize,

    /// Include messages from previous navigations
    #[arg(long)]
    pub include_preserved: bool,
}

/// Arguments for `console follow`.
#[derive(Args)]
pub struct ConsoleFollowArgs {
    /// Filter by message type (comma-separated: log,error,warn,info,debug,dir,table,trace,assert,count,timeEnd)
    #[arg(long, value_name = "TYPES", conflicts_with = "errors_only")]
    pub r#type: Option<String>,

    /// Show only error and assert messages (shorthand for --type error,assert)
    #[arg(long, conflicts_with = "type")]
    pub errors_only: bool,

    /// Auto-exit after the specified number of milliseconds
    #[arg(long)]
    pub timeout: Option<u64>,
}

/// Arguments for the `network` subcommand group.
#[derive(Args)]
pub struct NetworkArgs {
    #[command(subcommand)]
    pub command: NetworkCommand,
}

/// Network subcommands.
#[derive(Subcommand)]
pub enum NetworkCommand {
    /// List network requests or get details of a specific request
    #[command(
        long_about = "List captured network requests from the current page. Returns JSON with \
            each request's ID, method, URL, status, resource type, and timing. Filter by \
            resource type, URL pattern, HTTP status code, or HTTP method. Use --limit and \
            --page for pagination.",
        after_long_help = "\
EXAMPLES:
  # List recent requests
  chrome-cli network list

  # Filter by resource type
  chrome-cli network list --type xhr,fetch

  # Filter by URL pattern
  chrome-cli network list --url api.example.com

  # Filter by status code
  chrome-cli network list --status 4xx"
    )]
    List(NetworkListArgs),

    /// Get detailed information about a specific network request
    #[command(
        long_about = "Get detailed information about a specific network request by its numeric \
            ID. Returns JSON with full request and response headers, timing breakdown, and \
            body size. Use --save-request or --save-response to save the request or response \
            body to a file.",
        after_long_help = "\
EXAMPLES:
  # Get request details
  chrome-cli network get 42

  # Save the response body to a file
  chrome-cli network get 42 --save-response body.json

  # Save both request and response bodies
  chrome-cli network get 42 --save-request req.json --save-response resp.json"
    )]
    Get(NetworkGetArgs),

    /// Stream network requests in real-time (tail -f style)
    #[command(
        long_about = "Stream network requests in real time as they are made, similar to \
            'tail -f'. Each request is printed as a JSON line. Filter by resource type, \
            URL pattern, or HTTP method. Use --timeout to auto-exit after a specified \
            duration. Use --verbose to include request and response headers.",
        after_long_help = "\
EXAMPLES:
  # Stream all network requests
  chrome-cli network follow

  # Stream API requests only
  chrome-cli network follow --type xhr,fetch --url /api/

  # Stream with headers for 30 seconds
  chrome-cli network follow --verbose --timeout 30000"
    )]
    Follow(NetworkFollowArgs),
}

/// Arguments for `network list`.
#[derive(Args)]
pub struct NetworkListArgs {
    /// Filter by resource type (comma-separated: document,stylesheet,image,media,font,script,xhr,fetch,websocket,manifest,other)
    #[arg(long, value_name = "TYPES")]
    pub r#type: Option<String>,

    /// Filter by URL pattern (substring match)
    #[arg(long)]
    pub url: Option<String>,

    /// Filter by HTTP status code (exact like 404 or wildcard like 4xx)
    #[arg(long)]
    pub status: Option<String>,

    /// Filter by HTTP method (GET, POST, etc.)
    #[arg(long)]
    pub method: Option<String>,

    /// Maximum number of requests to return
    #[arg(long, default_value_t = 50)]
    pub limit: usize,

    /// Pagination page number (0-based)
    #[arg(long, default_value_t = 0)]
    pub page: usize,

    /// Include requests from previous navigations
    #[arg(long)]
    pub include_preserved: bool,
}

/// Arguments for `network get`.
#[derive(Args)]
pub struct NetworkGetArgs {
    /// Numeric request ID to inspect
    pub req_id: u64,

    /// Save request body to a file
    #[arg(long)]
    pub save_request: Option<PathBuf>,

    /// Save response body to a file
    #[arg(long)]
    pub save_response: Option<PathBuf>,
}

/// Arguments for `network follow`.
#[derive(Args)]
pub struct NetworkFollowArgs {
    /// Filter by resource type (comma-separated: document,stylesheet,image,media,font,script,xhr,fetch,websocket,manifest,other)
    #[arg(long, value_name = "TYPES")]
    pub r#type: Option<String>,

    /// Filter by URL pattern (substring match)
    #[arg(long)]
    pub url: Option<String>,

    /// Filter by HTTP method (GET, POST, etc.)
    #[arg(long)]
    pub method: Option<String>,

    /// Auto-exit after the specified number of milliseconds
    #[arg(long)]
    pub timeout: Option<u64>,

    /// Include request and response headers in stream output
    #[arg(long)]
    pub verbose: bool,
}

/// Arguments for `page resize`.
#[derive(Args)]
pub struct PageResizeArgs {
    /// Viewport size as WIDTHxHEIGHT (e.g. 1280x720)
    pub size: String,
}

/// Arguments for the `dom` subcommand group.
#[derive(Args)]
pub struct DomArgs {
    #[command(subcommand)]
    pub command: DomCommand,
}

/// DOM inspection and manipulation subcommands.
#[derive(Subcommand)]
pub enum DomCommand {
    /// Select elements by CSS selector or XPath
    #[command(
        long_about = "Query elements in the DOM by CSS selector (default) or XPath expression \
            (with --xpath). Returns a JSON array of matching elements with their node IDs, \
            tag names, attributes, and text content. Node IDs can be used with other dom \
            subcommands.",
        after_long_help = "\
EXAMPLES:
  # Select by CSS selector
  chrome-cli dom select \"h1\"

  # Select by XPath
  chrome-cli dom select \"//a[@href]\" --xpath

  # Select with a complex CSS selector
  chrome-cli dom select \"div.content > p:first-child\""
    )]
    Select(DomSelectArgs),

    /// Get a single attribute value from an element
    #[command(
        name = "get-attribute",
        long_about = "Read a single attribute value from a DOM element. The element can be \
            targeted by node ID (from 'dom select'), snapshot UID (from 'page snapshot'), \
            or CSS selector (prefixed with 'css:'). Returns the attribute name and value.",
        after_long_help = "\
EXAMPLES:
  # Get href by UID
  chrome-cli dom get-attribute s3 href

  # Get class by CSS selector
  chrome-cli dom get-attribute css:h1 class"
    )]
    GetAttribute(DomGetAttributeArgs),

    /// Get the text content of an element
    #[command(
        name = "get-text",
        long_about = "Read the textContent of a DOM element. Returns the combined text of \
            the element and all its descendants.",
        after_long_help = "\
EXAMPLES:
  # Get text by UID
  chrome-cli dom get-text s3

  # Get text by CSS selector
  chrome-cli dom get-text css:h1"
    )]
    GetText(DomNodeIdArgs),

    /// Get the outer HTML of an element
    #[command(
        name = "get-html",
        long_about = "Read the outerHTML of a DOM element, including the element itself and \
            all its children as an HTML string.",
        after_long_help = "\
EXAMPLES:
  # Get HTML by UID
  chrome-cli dom get-html s3

  # Get HTML by CSS selector
  chrome-cli dom get-html css:div.content"
    )]
    GetHtml(DomNodeIdArgs),

    /// Set an attribute on an element
    #[command(
        name = "set-attribute",
        long_about = "Set or update an attribute on a DOM element. Creates the attribute if \
            it doesn't exist, or updates its value if it does.",
        after_long_help = "\
EXAMPLES:
  # Set class attribute
  chrome-cli dom set-attribute s5 class \"highlight\"

  # Set data attribute by CSS selector
  chrome-cli dom set-attribute css:#main data-active true"
    )]
    SetAttribute(DomSetAttributeArgs),

    /// Set the text content of an element
    #[command(
        name = "set-text",
        long_about = "Replace the textContent of a DOM element, removing all child nodes \
            and setting the element's content to the given text.",
        after_long_help = "\
EXAMPLES:
  # Set text by UID
  chrome-cli dom set-text s3 \"New heading\"

  # Set text by CSS selector
  chrome-cli dom set-text css:h1 \"Updated Title\""
    )]
    SetText(DomSetTextArgs),

    /// Remove an element from the DOM
    #[command(
        long_about = "Remove a DOM element and all its children from the document. This is \
            irreversible within the current page session.",
        after_long_help = "\
EXAMPLES:
  # Remove by UID
  chrome-cli dom remove s3

  # Remove by CSS selector
  chrome-cli dom remove css:div.ad-banner"
    )]
    Remove(DomNodeIdArgs),

    /// Get computed CSS styles of an element
    #[command(
        name = "get-style",
        long_about = "Read the computed CSS styles of a DOM element. Without a property name, \
            returns all computed styles. With a property name, returns just that property's \
            value.",
        after_long_help = "\
EXAMPLES:
  # Get all computed styles
  chrome-cli dom get-style s3

  # Get a specific property
  chrome-cli dom get-style s3 display

  # Get style by CSS selector
  chrome-cli dom get-style css:h1 color"
    )]
    GetStyle(DomGetStyleArgs),

    /// Set the inline style of an element
    #[command(
        name = "set-style",
        long_about = "Set the inline style attribute of a DOM element. The style string replaces \
            the entire inline style. Use CSS property syntax.",
        after_long_help = "\
EXAMPLES:
  # Set inline style
  chrome-cli dom set-style s3 \"color: red; font-size: 24px\"

  # Set style by CSS selector
  chrome-cli dom set-style css:h1 \"display: none\""
    )]
    SetStyle(DomSetStyleArgs),

    /// Get the parent element
    #[command(
        long_about = "Navigate to the parent element of a DOM node. Returns the parent's \
            node ID, tag name, attributes, and text content.",
        after_long_help = "\
EXAMPLES:
  # Get parent of a UID
  chrome-cli dom parent s3

  # Get parent by CSS selector
  chrome-cli dom parent css:span.label"
    )]
    Parent(DomNodeIdArgs),

    /// List direct child elements
    #[command(
        long_about = "List the direct child elements (element nodes only, nodeType 1) of a \
            DOM node. Returns a JSON array of child elements.",
        after_long_help = "\
EXAMPLES:
  # List children by UID
  chrome-cli dom children s3

  # List children by CSS selector
  chrome-cli dom children css:div.container"
    )]
    Children(DomNodeIdArgs),

    /// List sibling elements
    #[command(
        long_about = "List the sibling elements of a DOM node (other children of the same \
            parent, excluding the target element itself).",
        after_long_help = "\
EXAMPLES:
  # List siblings by UID
  chrome-cli dom siblings s3

  # List siblings by CSS selector
  chrome-cli dom siblings css:li.active"
    )]
    Siblings(DomNodeIdArgs),

    /// Pretty-print the DOM tree
    #[command(
        long_about = "Display the DOM tree as indented plain text. By default shows the full \
            document tree. Use --depth to limit traversal depth and --root to start from a \
            specific element.",
        after_long_help = "\
EXAMPLES:
  # Show the full DOM tree
  chrome-cli dom tree

  # Limit depth to 3 levels
  chrome-cli dom tree --depth 3

  # Show tree from a specific element
  chrome-cli dom tree --root css:div.content"
    )]
    Tree(DomTreeArgs),
}

/// Arguments for `dom select`.
#[derive(Args)]
pub struct DomSelectArgs {
    /// CSS selector or XPath expression to query
    pub selector: String,

    /// Interpret the selector as an XPath expression instead of CSS
    #[arg(long)]
    pub xpath: bool,
}

/// Arguments for `dom get-attribute`.
#[derive(Args)]
pub struct DomGetAttributeArgs {
    /// Target element (node ID, UID like 's1', or CSS selector like 'css:#el')
    pub node_id: String,

    /// Attribute name to read
    pub attribute: String,
}

/// Arguments for `dom set-attribute`.
#[derive(Args)]
pub struct DomSetAttributeArgs {
    /// Target element (node ID, UID like 's1', or CSS selector like 'css:#el')
    pub node_id: String,

    /// Attribute name to set
    pub attribute: String,

    /// Attribute value
    pub value: String,
}

/// Arguments for `dom get-style`.
#[derive(Args)]
pub struct DomGetStyleArgs {
    /// Target element (node ID, UID like 's1', or CSS selector like 'css:#el')
    pub node_id: String,

    /// CSS property name (omit for all computed styles)
    pub property: Option<String>,
}

/// Arguments for `dom set-style`.
#[derive(Args)]
pub struct DomSetStyleArgs {
    /// Target element (node ID, UID like 's1', or CSS selector like 'css:#el')
    pub node_id: String,

    /// CSS style text (e.g. "color: red; font-size: 24px")
    pub style: String,
}

/// Arguments for `dom set-text`.
#[derive(Args)]
pub struct DomSetTextArgs {
    /// Target element (node ID, UID like 's1', or CSS selector like 'css:#el')
    pub node_id: String,

    /// Text content to set
    pub text: String,
}

/// Shared arguments for dom subcommands that take only a node ID.
///
/// Used by get-text, get-html, remove, parent, children, siblings.
#[derive(Args)]
pub struct DomNodeIdArgs {
    /// Target element (node ID, UID like 's1', or CSS selector like 'css:#el')
    pub node_id: String,
}

/// Arguments for `dom tree`.
#[derive(Args)]
pub struct DomTreeArgs {
    /// Maximum tree depth to display
    #[arg(long)]
    pub depth: Option<u32>,

    /// Start the tree from a specific element (node ID, UID, or CSS selector)
    #[arg(long)]
    pub root: Option<String>,
}

/// Arguments for the `emulate` subcommand group.
#[derive(Args)]
pub struct EmulateArgs {
    #[command(subcommand)]
    pub command: EmulateCommand,
}

/// Emulate subcommands.
#[derive(Subcommand)]
pub enum EmulateCommand {
    /// Apply one or more emulation overrides
    #[command(
        long_about = "Apply one or more device or network emulation overrides. Multiple \
            overrides can be combined in a single command (e.g., viewport + network + user \
            agent). Overrides persist until 'emulate reset' is called or the browser is closed. \
            Note: --geolocation and --no-geolocation are mutually exclusive, as are \
            --user-agent and --no-user-agent.",
        after_long_help = "\
EXAMPLES:
  # Emulate a mobile device
  chrome-cli emulate set --viewport 375x667 --device-scale 2 --mobile

  # Simulate slow network
  chrome-cli emulate set --network 3g

  # Set geolocation (San Francisco)
  chrome-cli emulate set --geolocation 37.7749,-122.4194

  # Force dark mode with custom user agent
  chrome-cli emulate set --color-scheme dark --user-agent \"CustomBot/1.0\"

  # Throttle CPU (4x slowdown)
  chrome-cli emulate set --cpu 4"
    )]
    Set(EmulateSetArgs),

    /// Clear all emulation overrides
    #[command(
        long_about = "Clear all device and network emulation overrides, restoring the browser \
            to its default settings. This removes viewport, user agent, geolocation, network \
            throttling, CPU throttling, and color scheme overrides.",
        after_long_help = "\
EXAMPLES:
  # Reset all overrides
  chrome-cli emulate reset"
    )]
    Reset,

    /// Show current emulation settings
    #[command(
        long_about = "Display the current emulation state including viewport dimensions, \
            user agent, device scale factor, network conditions, CPU throttling, and color \
            scheme. Returns JSON with the active emulation configuration.",
        after_long_help = "\
EXAMPLES:
  # Check emulation status
  chrome-cli emulate status"
    )]
    Status,
}

/// Arguments for `emulate set`.
#[allow(clippy::struct_excessive_bools)]
#[derive(Args)]
pub struct EmulateSetArgs {
    /// Network condition profile: offline, slow-4g, 4g, 3g, none
    #[arg(long, value_enum)]
    pub network: Option<NetworkProfile>,

    /// CPU throttling rate (1 = no throttling, 2-20 = slowdown factor)
    #[arg(long, value_parser = clap::value_parser!(u32).range(1..=20))]
    pub cpu: Option<u32>,

    /// Set geolocation override as LAT,LONG (e.g. 37.7749,-122.4194; conflicts with --no-geolocation)
    #[arg(long, conflicts_with = "no_geolocation")]
    pub geolocation: Option<String>,

    /// Clear geolocation override (conflicts with --geolocation)
    #[arg(long, conflicts_with = "geolocation")]
    pub no_geolocation: bool,

    /// Set custom user agent string (conflicts with --no-user-agent)
    #[arg(long, conflicts_with = "no_user_agent")]
    pub user_agent: Option<String>,

    /// Reset user agent to browser default (conflicts with --user-agent)
    #[arg(long, conflicts_with = "user_agent")]
    pub no_user_agent: bool,

    /// Force color scheme: dark, light, auto
    #[arg(long, value_enum)]
    pub color_scheme: Option<ColorScheme>,

    /// Set viewport dimensions as WIDTHxHEIGHT (e.g. 375x667)
    #[arg(long)]
    pub viewport: Option<String>,

    /// Set device pixel ratio (e.g. 2.0)
    #[arg(long)]
    pub device_scale: Option<f64>,

    /// Emulate mobile device (touch events, mobile viewport)
    #[arg(long)]
    pub mobile: bool,
}

/// Network condition profiles for emulation.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum NetworkProfile {
    /// Fully offline (no network)
    Offline,
    /// Slow 4G (150ms latency, 1.6 Mbps down, 750 Kbps up)
    #[value(name = "slow-4g")]
    Slow4g,
    /// 4G (20ms latency, 4 Mbps down, 3 Mbps up)
    #[value(name = "4g")]
    FourG,
    /// 3G (100ms latency, 750 Kbps down, 250 Kbps up)
    #[value(name = "3g")]
    ThreeG,
    /// No throttling (disable network emulation)
    None,
}

/// Color scheme for emulation.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ColorScheme {
    /// Force dark mode
    Dark,
    /// Force light mode
    Light,
    /// Reset to browser default
    Auto,
}

/// Arguments for the `config` subcommand group.
#[derive(Args)]
pub struct ConfigArgs {
    #[command(subcommand)]
    pub command: ConfigCommand,
}

/// Config management subcommands.
#[derive(Subcommand)]
pub enum ConfigCommand {
    /// Display the resolved configuration from all sources
    #[command(
        long_about = "Display the fully resolved configuration by merging all sources in \
            priority order: CLI flags > environment variables > config file > defaults. \
            Returns JSON showing every setting and its effective value. Useful for debugging \
            which settings are active.",
        after_long_help = "\
EXAMPLES:
  # Show resolved config
  chrome-cli config show

  # Show config from a specific file
  chrome-cli --config ./my-config.toml config show"
    )]
    Show,

    /// Create a default config file with commented example values
    #[command(
        long_about = "Create a new configuration file with all available settings documented \
            as comments. By default, the file is created at the XDG config directory \
            (~/.config/chrome-cli/config.toml on Linux, ~/Library/Application Support/\
            chrome-cli/config.toml on macOS). Use --path to specify a custom location. \
            Will not overwrite an existing file.",
        after_long_help = "\
EXAMPLES:
  # Create default config file
  chrome-cli config init

  # Create at a custom path
  chrome-cli config init --path ./my-config.toml"
    )]
    Init(ConfigInitArgs),

    /// Show the active config file path (or null if none)
    #[command(
        long_about = "Show the path of the active configuration file. Searches in priority \
            order: --config flag, $CHROME_CLI_CONFIG env var, project-local \
            (.chrome-cli.toml), XDG config dir, home directory (~/.chrome-cli.toml). \
            Returns JSON with {\"path\": \"...\"} or {\"path\": null} if no config file is found.",
        after_long_help = "\
EXAMPLES:
  # Show active config path
  chrome-cli config path"
    )]
    Path,
}

/// Arguments for `config init`.
#[derive(Args)]
pub struct ConfigInitArgs {
    /// Create config file at a custom path instead of the default XDG location
    #[arg(long)]
    pub path: Option<PathBuf>,
}

/// Arguments for the `completions` subcommand.
#[derive(Args)]
pub struct CompletionsArgs {
    /// Shell to generate completions for (bash, zsh, fish, powershell, elvish)
    pub shell: Shell,
}

/// Arguments for the `man` subcommand.
#[derive(Args)]
pub struct ManArgs {
    /// Subcommand to display man page for (omit for top-level)
    pub command: Option<String>,
}

/// Arguments for the `examples` subcommand.
#[derive(Args)]
pub struct ExamplesArgs {
    /// Command group to show examples for (e.g., navigate, tabs, page)
    pub command: Option<String>,
}

/// Arguments for the `capabilities` subcommand.
#[derive(Args)]
pub struct CapabilitiesArgs {
    /// Show capabilities for a specific command only
    #[arg(long)]
    pub command: Option<String>,

    /// Minimal output: command names and descriptions only
    #[arg(long)]
    pub compact: bool,
}