flow-wm 0.1.0

A scrolling, infinite-horizontal-canvas tiling window manager for Windows
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
//! flow — FlowWM CLI client.
//!
//! Sends commands to the `flowd` daemon via a Windows named pipe. Commands fall
//! into four groups:
//!
//! | Group | Commands |
//! |-------|----------|
//! | Lifecycle | `start`, `stop`, `enable-autostart`, `disable-autostart` |
//! | Config | `config init` / `reload` / `edit` / `path` / `check` |
//! | Query | `query all` |
//! | Dispatch | `dispatch focus\|swap-column\|move-window\|merge-column\|promote\|expand-column\|shrink-column\|center\|close-window\|set-window\|switch-workspace\|move-to-workspace`, plus stub `swap-workspace` |
//!
//! See the developer guide's *IPC & Watchdog* chapter
//! (`docs/src/dev-guide/ipc-and-watchdog.md`) for the full command reference.
//!
//! # Configuration
//!
//! The config directory is resolved via a priority chain:
//!
//! 1. `--config <dir>` flag on `flow start` (passed to the daemon via the
//!    `FLOW_CONFIG_DIR` env var)
//! 2. `FLOW_CONFIG_DIR` environment variable
//! 3. Default: `%USERPROFILE%\.config\flow\`
//!
//! The `flow config init/reload/edit/path/check` commands resolve the config
//! directory without contacting the daemon — they operate on local files only.
//! Only `flow config reload` sends an IPC message to the running daemon.

use std::os::windows::process::CommandExt;
use std::path::Path;
use std::process::Command;
use std::time::Duration;

use clap::{Parser, Subcommand};
use windows::Win32::UI::WindowsAndMessaging::AllowSetForegroundWindow;

use flow_wm::autostart;
use flow_wm::common::Direction;
use flow_wm::config;
use flow_wm::ipc::message::SocketMessage;
use flow_wm::ipc::message::SocketResponse;
use flow_wm::ipc::message::WindowMode;
use flow_wm::ipc::transport;

/// Maximum time to wait for the daemon to become ready after spawning.
const DAEMON_START_TIMEOUT: Duration = Duration::from_secs(5);

#[derive(Parser)]
#[command(name = "flow", version, about = "FlowWM CLI")]
#[command(propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

/// Top-level commands for the flow CLI client.
#[derive(Debug, Subcommand)]
enum Commands {
    /// Start the flowd daemon in the background.
    Start {
        /// Config directory path. Overrides FLOW_CONFIG_DIR env var and default path.
        #[arg(long)]
        config: Option<String>,
        /// Optional log file path.
        ///
        /// Forwarded to the spawned daemon as `--log-file`. When set, flowd
        /// redirects all of its logging to this exact file (truncated on each
        /// start) instead of the default date-stamped log — useful for
        /// capturing a clean, isolated debug log for a single run. The log
        /// level is still controlled by the `RUST_LOG` environment variable.
        #[arg(long, value_name = "PATH")]
        log_file: Option<String>,
        /// Also launch the user's `flow.ahk` keybinding script once the daemon
        /// is ready. The script is launched via its `.ahk` shell association
        /// and its PID is tracked so `flow stop --ahk` can terminate it.
        #[arg(long)]
        ahk: bool,
    },
    /// Stop the running flowd daemon.
    Stop {
        /// Also stop the AutoHotkey script launched by `flow start --ahk`.
        #[arg(long)]
        ahk: bool,
    },
    /// Manage configuration files.
    Config {
        #[command(subcommand)]
        command: ConfigCommands,
    },
    /// Query daemon state.
    Query {
        #[command(subcommand)]
        command: QueryCommands,
    },
    /// Dispatch a command to the daemon (focus, swap, scroll, etc.).
    ///
    /// Use `flow dispatch help` to see available subcommands. New action
    /// categories will be added here as needed.
    Dispatch {
        #[command(subcommand)]
        command: DispatchCommands,
    },
    /// Create the login autostart shortcut in `shell:startup`.
    EnableAutostart {
        /// Bake `--ahk` into the shortcut's args so login also launches
        /// `flow.ahk` alongside the daemon.
        #[arg(long)]
        ahk: bool,
    },
    /// Remove the login autostart shortcut from `shell:startup`.
    DisableAutostart,
}

/// Configuration management subcommands.
///
/// These commands (except `reload`) operate on local config files without
/// contacting the daemon. Only `reload` sends an IPC message.
#[derive(Debug, Subcommand)]
enum ConfigCommands {
    /// Initialize config directory with default files.
    ///
    /// Pass `--ahk` to also write `flow.ahk`, a ready-to-use AutoHotkey v2
    /// keybinding script that drives FlowWM via the `flow` CLI. See the
    /// developer guide's *IPC & Watchdog* chapter
    /// (`docs/src/dev-guide/ipc-and-watchdog.md`) for the command reference.
    Init {
        /// Also write `flow.ahk` (a bundled AutoHotkey v2 keybinding script)
        /// into the config directory. Existing files are never overwritten.
        #[arg(long)]
        ahk: bool,
    },
    /// Reload daemon configuration from disk.
    Reload,
    /// Open config directory in the system editor.
    Edit,
    /// Print the resolved config directory path.
    Path,
    /// Validate configuration files.
    Check,
}

/// Query subcommands.
#[derive(Debug, Subcommand)]
enum QueryCommands {
    /// Dump all tracked windows with full debug info (state, rect, col/row, etc.).
    All,
}

/// Dispatch subcommands — one per action category.
///
/// Each variant wraps a further subcommand tree so the CLI stays organized as
/// more actions are added (swap-column, swap-window, etc.).
///
/// # Layout pipeline
///
/// Every dispatch command that changes layout flows through the same 3-step
/// pipeline inside the daemon:
///
/// 1. **Mutate** the virtual layout (e.g. widen the focused column).
///    Widening a column naturally pushes every column to its right further
///    along the virtual canvas — no explicit per-window shift is needed.
/// 2. **Project** the virtual layout into actual screen coordinates, adjusting
///    the viewport so the focused column stays visible (`ensure_column_visible`).
/// 3. **Animate** the new actual layout — the animation layer compares each
///    window's target rect against its real on-screen position and tweens
///    only the windows that differ.
///
/// The CLI's only job is to send the right [`SocketMessage`]; the daemon
/// owns the entire pipeline above.
#[derive(Debug, Subcommand)]
enum DispatchCommands {
    /// Focus a window in the given direction.
    Focus {
        #[command(subcommand)]
        direction: FocusDirection,
    },
    /// Swap the focused column with its left/right neighbour.
    SwapColumn {
        #[command(subcommand)]
        direction: HorizontalDirection,
    },
    /// Move the focused window in the given direction.
    ///
    /// This is a semantic command — the daemon decides what "move" means
    /// based on window state and direction:
    /// - tiled left/right → column swap (cross-column move is deferred);
    /// - tiled up/down → within-column window swap;
    /// - floating → pixel nudge (deferred).
    MoveWindow {
        #[command(subcommand)]
        direction: MoveDirection,
    },
    /// Merge the focused window's row into the adjacent column.
    ///
    /// Maps to [`SocketMessage::MergeColumn`]. The focused window is
    /// detached from its column and appended as a new bottom row of the
    /// neighbour column; both columns' row heights are redistributed.
    MergeColumn {
        #[command(subcommand)]
        direction: HorizontalDirection,
    },
    /// Promote the focused window out of its column into a new standalone column.
    ///
    /// Maps to [`SocketMessage::Promote`]. The focused window is extracted
    /// into a new single-row column placed to the left or right of the
    /// source column. No-op when the window is already alone in its column.
    Promote {
        #[command(subcommand)]
        direction: HorizontalDirection,
    },

    /// Expand the focused column width by one column step.
    ///
    /// Sends [`SocketMessage::ExpandColumn`]. The daemon widens the focused
    /// column to the next `column_width` boundary and animates the result.
    ExpandColumn,
    /// Shrink the focused column width by one column step.
    ///
    /// Sends [`SocketMessage::ShrinkColumn`]. The daemon narrows the focused
    /// column to the previous `column_width` boundary and animates the result.
    ShrinkColumn,
    /// Center the viewport so the focused column lands at the monitor midpoint.
    ///
    /// Sends [`SocketMessage::Center`]. The daemon slides the viewport so the
    /// focused column lands at the monitor midpoint using the variable-width
    /// prefix sum — works correctly even with expanded or shrunk columns.
    Center,
    /// Close the currently focused window.
    ///
    /// Sends [`SocketMessage::CloseWindow`]. The daemon asks the focused
    /// window to close itself gently via Win32 `WM_CLOSE` — the same message
    /// Windows sends when the user clicks the window's ✕ button — so the
    /// application can run its normal shutdown logic (prompt to save unsaved
    /// work, release resources, etc.). The window is removed from the layout
    /// automatically once Win32 reports its destruction.
    CloseWindow,
    /// Set the focused window's tiling mode.
    ///
    /// Maps to [`SocketMessage::SetWindow`]. Sends
    /// `flow dispatch set-window float|tile|cycle` to the daemon, which
    /// transitions the focused window between floating and tiling modes.
    SetWindow {
        #[command(subcommand)]
        mode: WindowMode,
    },

    // --- Workspace (niri-style virtual desktop) ---
    //
    // These three subcommands form the CLI surface for the upcoming
    // vertical-scrolling workspace system. The daemon currently returns a
    // "not yet implemented" error for each — the protocol shape is locked in
    // now so keybindings and documentation can stabilise while the workspace
    // animation design is finalised.
    /// Switch the active workspace.
    ///
    /// Maps to [`SocketMessage::SwitchWorkspace`]. Sends
    /// `flow dispatch switch-workspace <id>` to the daemon, which slides the
    /// requested workspace into the viewport and parks the previously active
    /// one above or below it in a single coordinated animation.
    SwitchWorkspace {
        /// Identifier of the workspace to switch to (niri-style `u32`).
        workspace_id: u32,
    },
    /// Swap the active workspace with another workspace.
    ///
    /// Maps to [`SocketMessage::SwapWorkspace`]. Sends
    /// `flow dispatch swap-workspace <id>` to the daemon, which will
    /// (eventually) exchange the positions of the active workspace and the
    /// target in the monitor's vertical workspace stack, with focus following
    /// the originally active workspace.
    SwapWorkspace {
        /// Identifier of the workspace to swap with the active one.
        workspace_id: u32,
    },
    /// Move the focused window to another workspace.
    ///
    /// Maps to [`SocketMessage::MoveWindowToWorkspace`]. Sends
    /// `flow dispatch move-to-workspace <id>` to the daemon, which detaches the
    /// focused window from the active workspace's `ScrollingSpace` (with
    /// local focus succession — no OS foreground focus push) and re-inserts
    /// it into the target workspace's `ScrollingSpace` after its focused
    /// column. Focus stays on the source workspace.
    ///
    /// The CLI command name is the shorter `move-to-workspace` for brevity,
    /// even though the underlying IPC variant is `MoveWindowToWorkspace`
    /// (mirroring the sibling `move-window` operation).
    #[command(name = "move-to-workspace")]
    MoveWindowToWorkspace {
        /// Identifier of the destination workspace.
        workspace_id: u32,
    },
}

/// Cardinal direction for `flow dispatch focus <dir>`.
#[derive(Debug, Subcommand)]
enum FocusDirection {
    /// Focus the window to the left.
    Left,
    /// Focus the window to the right.
    Right,
    /// Focus the window above.
    Up,
    /// Focus the window below.
    Down,
}

/// Horizontal direction for `flow dispatch swap-column|merge-column|promote <dir>`.
///
/// Only left/right is offered: column swaps, merges, and promotes are
/// inherently horizontal operations between adjacent columns.
#[derive(Debug, Subcommand)]
enum HorizontalDirection {
    /// Left.
    Left,
    /// Right.
    Right,
}

/// Cardinal direction for `flow dispatch move-window <dir>`.
///
/// All four directions are accepted: left/right resolve to a column swap
/// (until a real cross-column move lands), and up/down resolve to a
/// within-column window swap.
#[derive(Debug, Subcommand)]
enum MoveDirection {
    /// Left.
    Left,
    /// Right.
    Right,
    /// Up.
    Up,
    /// Down.
    Down,
}

fn main() {
    let cli = Cli::parse();

    let result = match cli.command {
        Commands::Start {
            config,
            log_file,
            ahk,
        } => cmd_start(config, log_file, ahk),
        Commands::Stop { ahk } => cmd_stop(ahk),
        Commands::Config { command } => cmd_config(command),
        Commands::Query { command } => cmd_query(command),
        Commands::Dispatch { command } => cmd_dispatch(command),
        Commands::EnableAutostart { ahk } => cmd_enable_autostart(ahk),
        Commands::DisableAutostart => cmd_disable_autostart(),
    };

    if let Err(e) = result {
        eprintln!("flow: {e}");
        std::process::exit(1);
    }
}

/// Start the daemon and wait for it to become ready.
///
/// If a `--config <dir>` override is provided, sets the `FLOW_CONFIG_DIR`
/// environment variable before spawning the daemon process. The daemon reads
/// this variable on startup to locate its config files, so the override is
/// propagated transparently through process inheritance.
///
/// If a `--log-file <path>` override is provided, it is forwarded to the
/// daemon as a `--log-file` CLI argument (see [`spawn_daemon`]). Unlike
/// `--config`, this is passed explicitly on the command line rather than via
/// an environment variable.
///
/// When `ahk` is true, the user's `flow.ahk` is launched via
/// [`autostart::spawn_ahk_script`] after the daemon is ready, so the daemon
/// is already listening when the first hotkey fires.
///
/// # Design Decision
///
/// We use [`std::env::set_var`] rather than `Command::env()` because the
/// daemon is spawned via [`spawn_daemon`] which also needs to handle detached
/// process creation flags. Setting the env var in the current process ensures
/// it is inherited by the child regardless of the spawn path.
///
/// # Errors
///
/// Returns an error string if:
/// - The daemon is already running.
/// - The user's `flow.toml` cannot be parsed (pre-flight config check fails).
/// - The daemon binary cannot be found.
/// - The daemon fails to spawn.
/// - The daemon does not become ready within [`DAEMON_START_TIMEOUT`].
/// - `ahk` is true and `flow.ahk` cannot be launched.
fn cmd_start(
    config_override: Option<String>,
    log_file_override: Option<String>,
    ahk: bool,
) -> Result<(), String> {
    // Set env var before any daemon interaction so the spawned child inherits it.
    if let Some(ref dir) = config_override {
        // SAFETY: This is called in the CLI process before spawning the daemon
        // child. There are no other threads reading this env var at this point,
        // and the CLI is a short-lived process with no concurrent Rust code.
        unsafe { std::env::set_var(config::dirs::CONFIG_DIR_ENV, dir) };
    }

    if transport::is_daemon_running() {
        return Err("daemon is already running".into());
    }

    // Pre-flight config check: surface `flow.toml`/`flow-rules.toml` errors on the
    // user's terminal before spawning, because the detached daemon's
    // stdout/stderr are discarded. Reuses the daemon's own loaders (same crate),
    // so the verdict matches — no desync between client and daemon.
    let config_dir = config::dirs::resolve_config_dir(config_override.as_deref().map(Path::new));
    preflight_config_check(&config_dir)?;

    spawn_daemon(log_file_override.as_deref())?;
    wait_for_daemon()?;

    println!("flow: daemon started");

    if ahk {
        // Launch AHK after the daemon is listening so the first hotkey lands.
        let pid = autostart::spawn_ahk_script()?;
        println!("flow: launched flow.ahk (pid {pid})");
    }

    Ok(())
}

/// Run a pre-flight config check on the user's terminal before spawning the daemon.
///
/// The detached daemon's stdout/stderr are discarded, so its config-load errors
/// are invisible; this surfaces them on the user's terminal before spawn. The
/// load-error policy and the race-window rationale live in
/// `docs/src/dev-guide/config-and-persistence.md`.
///
/// # Errors
///
/// `Err(String)` only if `flow.toml` cannot be loaded (identifying file and
/// cause). A `flow-rules.toml` failure is warned on stderr and does *not* error.
fn preflight_config_check(config_dir: &Path) -> Result<(), String> {
    let app_path = config::dirs::user_app_config_path_in(config_dir);
    if let Err(e) = config::load_app_config(&app_path) {
        // Fatal: surface why+where and refuse to spawn.
        return Err(format!("flow: cannot start: {e}"));
    }

    let rules_path = config::dirs::user_rules_path_in(config_dir);
    if let Err(e) = config::load_rules_config(&rules_path) {
        // Non-fatal: warn on stderr but allow startup with default rules.
        eprintln!("flow: warning: {e}; using default window rules");
    }
    Ok(())
}

/// Send a Stop message to the daemon.
///
/// When `ahk` is true, the AutoHotkey script launched by `flow start --ahk`
/// is terminated via [`autostart::stop_ahk_script`] **after** the daemon has
/// stopped, so a live daemon never loses its keybindings mid-dispatch.
///
/// # Errors
///
/// Returns an error string if the daemon cannot be reached, or if `ahk` is
/// true and terminating the AHK process fails.
fn cmd_stop(ahk: bool) -> Result<(), String> {
    send_command(SocketMessage::Stop, "daemon stopped")?;
    if ahk {
        let stopped = autostart::stop_ahk_script()?;
        if stopped {
            println!("flow: stopped flow.ahk");
        } else {
            println!("flow: no tracked flow.ahk to stop");
        }
    }
    Ok(())
}

/// Create the login autostart shortcut in `shell:startup`.
///
/// When `ahk` is true, the shortcut's args become `start --ahk` so login also
/// launches `flow.ahk`.
///
/// # Errors
///
/// Returns an error string on shortcut-creation failure (see
/// [`autostart::enable_autostart`]).
fn cmd_enable_autostart(ahk: bool) -> Result<(), String> {
    let report = autostart::enable_autostart(ahk)?;
    println!(
        "flow: autostart {} at {}",
        if ahk { "enabled (--ahk)" } else { "enabled" },
        report.shortcut.display()
    );
    Ok(())
}

/// Remove the login autostart shortcut from `shell:startup`.
///
/// Idempotent: silently succeeds if no shortcut exists.
///
/// # Errors
///
/// Returns an error string only on filesystem errors other than `NotFound`.
fn cmd_disable_autostart() -> Result<(), String> {
    let report = autostart::disable_autostart()?;
    println!("flow: autostart disabled ({})", report.shortcut.display());
    Ok(())
}

/// Dispatch a configuration subcommand.
///
/// Most config commands operate locally (no daemon contact). Only `Reload`
/// sends an IPC message to the running daemon.
fn cmd_config(command: ConfigCommands) -> Result<(), String> {
    match command {
        ConfigCommands::Init { ahk } => cmd_config_init(ahk),
        ConfigCommands::Reload => cmd_config_reload(),
        ConfigCommands::Edit => cmd_config_edit(),
        ConfigCommands::Path => cmd_config_path(),
        ConfigCommands::Check => cmd_config_check(),
    }
}

/// Initialize the config directory with default files.
///
/// Calls [`config::dirs::config_dir`] to resolve the config directory, then
/// [`config::init_config_dir`] to create it and write default config files
/// (`flow.toml`, `flow-rules.toml`) and JSON Schemas. Existing files are never
/// overwritten.
///
/// When `ahk` is set, also writes `flow.ahk` — a bundled AutoHotkey v2
/// keybinding script — via [`config::write_ahk_template`]. This is a
/// convenience for users who want to drive FlowWM via AutoHotkey without
/// authoring their own script.
///
/// # Errors
///
/// Returns an error string if directory creation or file writing fails.
fn cmd_config_init(ahk: bool) -> Result<(), String> {
    let dir = config::dirs::config_dir();
    config::init_config_dir(&dir)?;
    println!("flow: config initialized at {}", dir.display());
    if ahk {
        let ahk_path = dir.join("flow.ahk");
        match config::write_ahk_template(&dir)? {
            true => println!("flow: wrote flow.ahk at {}", ahk_path.display()),
            false => println!(
                "flow: flow.ahk already exists at {} (left untouched)",
                ahk_path.display()
            ),
        }
    }
    Ok(())
}

/// Send a ReloadConfig message to the daemon.
///
/// This is the only `flow config` subcommand that requires the daemon to be
/// running. It tells the daemon to re-read all config files from disk.
fn cmd_config_reload() -> Result<(), String> {
    send_command(SocketMessage::ReloadConfig, "configuration reloaded")
}

/// Open the config directory in the system editor.
///
/// Resolves the editor command from:
/// 1. `EDITOR` environment variable
/// 2. `VISUAL` environment variable
/// 3. `notepad.exe` (Windows default)
///
/// Opens the **directory** (not a specific file) so the user can browse all
/// config files. Waits for the editor to exit before returning.
///
/// # Errors
///
/// Returns an error string if:
/// - No editor can be determined.
/// - The editor process fails to start.
/// - The editor exits with a non-zero status.
fn cmd_config_edit() -> Result<(), String> {
    let dir = config::dirs::config_dir();
    let editor = resolve_editor()?;

    println!("flow: opening {} in {}", dir.display(), editor);

    let status = Command::new(&editor)
        .arg(&dir)
        .status()
        .map_err(|e| format!("failed to start editor '{}': {e}", editor))?;

    if !status.success() {
        return Err(format!(
            "editor '{}' exited with status {}",
            editor,
            status
                .code()
                .map_or_else(|| "unknown".to_string(), |c| c.to_string())
        ));
    }

    Ok(())
}

/// Print the resolved config directory path.
///
/// Outputs just the path (one line) to stdout, making it useful for scripting
/// and shell integration.
fn cmd_config_path() -> Result<(), String> {
    let dir = config::dirs::config_dir();
    println!("{}", dir.display());
    Ok(())
}

/// Validate configuration files without loading them into the daemon.
///
/// Calls [`config::check_config`] which reads and validates both `flow.toml` and
/// `flow-rules.toml` if they exist. Missing files are not errors — they simply
/// mean defaults will be used.
///
/// # Errors
///
/// Returns an error string if any config file fails validation (parse error or
/// invalid field values).
fn cmd_config_check() -> Result<(), String> {
    let dir = config::dirs::config_dir();
    config::check_config(&dir)?;
    println!("flow: configuration is valid");
    Ok(())
}

/// Dispatch a query subcommand.
fn cmd_query(command: QueryCommands) -> Result<(), String> {
    match command {
        QueryCommands::All => cmd_query_all(),
    }
}

/// Dump all tracked windows from the daemon as pretty-printed JSON.
fn cmd_query_all() -> Result<(), String> {
    let response = transport::send_message(&SocketMessage::QueryWindowsAll)
        .map_err(|e| format!("failed to send command: {e}"))?;

    match response {
        SocketResponse::Data { payload } => {
            let formatted =
                serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string());
            println!("{formatted}");
            Ok(())
        }
        SocketResponse::Error { message } => Err(format!("daemon error: {message}")),
        SocketResponse::Ok => {
            println!("flow: ok");
            Ok(())
        }
    }
}

/// Dispatch a dispatch subcommand.
///
/// Routes each [`DispatchCommands`] variant to its handler. New action
/// categories will be added here as match arms.
fn cmd_dispatch(command: DispatchCommands) -> Result<(), String> {
    match command {
        DispatchCommands::Focus { direction } => cmd_dispatch_focus(direction),
        DispatchCommands::SwapColumn { direction } => cmd_dispatch_swap_column(direction),
        DispatchCommands::MoveWindow { direction } => cmd_dispatch_move_window(direction),
        DispatchCommands::MergeColumn { direction } => cmd_dispatch_merge_column(direction),
        DispatchCommands::Promote { direction } => cmd_dispatch_promote(direction),
        DispatchCommands::ExpandColumn => {
            send_command(SocketMessage::ExpandColumn, "column expanded")
        }
        DispatchCommands::ShrinkColumn => {
            send_command(SocketMessage::ShrinkColumn, "column shrunk")
        }
        DispatchCommands::Center => send_command(SocketMessage::Center, "viewport centered"),
        DispatchCommands::CloseWindow => send_command(SocketMessage::CloseWindow, "window closed"),
        DispatchCommands::SetWindow { mode } => cmd_dispatch_set_window(mode),
        DispatchCommands::SwitchWorkspace { workspace_id } => send_command(
            SocketMessage::SwitchWorkspace { workspace_id },
            "workspace switched",
        ),
        DispatchCommands::SwapWorkspace { workspace_id } => send_command(
            SocketMessage::SwapWorkspace { workspace_id },
            "workspace swapped",
        ),
        DispatchCommands::MoveWindowToWorkspace { workspace_id } => send_command(
            SocketMessage::MoveWindowToWorkspace { workspace_id },
            "window moved to workspace",
        ),
    }
}

/// Send a focus-direction command to the daemon.
fn cmd_dispatch_focus(direction: FocusDirection) -> Result<(), String> {
    let msg = match direction {
        FocusDirection::Left => SocketMessage::FocusLeft,
        FocusDirection::Right => SocketMessage::FocusRight,
        FocusDirection::Up => SocketMessage::FocusUp,
        FocusDirection::Down => SocketMessage::FocusDown,
    };
    send_command(msg, "focus changed")
}

/// Send a column-swap command to the daemon.
///
/// Maps `flow dispatch swap-column left|right` to [`SocketMessage::SwapColumn`].
fn cmd_dispatch_swap_column(direction: HorizontalDirection) -> Result<(), String> {
    let msg = match direction {
        HorizontalDirection::Left => SocketMessage::SwapColumn {
            direction: Direction::Left,
        },
        HorizontalDirection::Right => SocketMessage::SwapColumn {
            direction: Direction::Right,
        },
    };
    send_command(msg, "column swapped")
}

/// Send a semantic move-window command to the daemon.
///
/// Maps `flow dispatch move-window left|right|up|down` to [`SocketMessage::MoveWindow`].
/// The daemon translates this into a concrete action based on window state
/// and direction (column swap horizontally, row swap vertically).
fn cmd_dispatch_move_window(direction: MoveDirection) -> Result<(), String> {
    let msg = match direction {
        MoveDirection::Left => SocketMessage::MoveWindow {
            direction: Direction::Left,
        },
        MoveDirection::Right => SocketMessage::MoveWindow {
            direction: Direction::Right,
        },
        MoveDirection::Up => SocketMessage::MoveWindow {
            direction: Direction::Up,
        },
        MoveDirection::Down => SocketMessage::MoveWindow {
            direction: Direction::Down,
        },
    };
    send_command(msg, "window moved")
}

/// Send a merge-column command to the daemon.
///
/// Maps `flow dispatch merge-column left|right` to [`SocketMessage::MergeColumn`].
/// The focused window is merged into the adjacent column as a new bottom row.
fn cmd_dispatch_merge_column(direction: HorizontalDirection) -> Result<(), String> {
    let msg = match direction {
        HorizontalDirection::Left => SocketMessage::MergeColumn {
            direction: Direction::Left,
        },
        HorizontalDirection::Right => SocketMessage::MergeColumn {
            direction: Direction::Right,
        },
    };
    send_command(msg, "column merged")
}

/// Send a promote command to the daemon.
///
/// Maps `flow dispatch promote left|right` to [`SocketMessage::Promote`]. The
/// focused window is extracted into a new single-row column on the chosen side.
fn cmd_dispatch_promote(direction: HorizontalDirection) -> Result<(), String> {
    let msg = match direction {
        HorizontalDirection::Left => SocketMessage::Promote {
            direction: Direction::Left,
        },
        HorizontalDirection::Right => SocketMessage::Promote {
            direction: Direction::Right,
        },
    };
    send_command(msg, "window promoted")
}

/// Send a set-window-mode command to the daemon.
///
/// Maps `flow dispatch set-window float|tile|cycle` to [`SocketMessage::SetWindow`].
fn cmd_dispatch_set_window(mode: WindowMode) -> Result<(), String> {
    let msg = SocketMessage::SetWindow { mode };
    let label = match mode {
        WindowMode::Float => "float",
        WindowMode::Tile => "tile",
        WindowMode::Cycle => "cycle",
    };
    send_command(msg, &format!("window set to {label}"))
}

/// Grant the daemon one-shot foreground-activation permission via
/// `AllowSetForegroundWindow(ASFW_ANY)`, so its next `SetForegroundWindow`
/// isn't refused by the foreground lock. Must be re-granted per command (the
/// grant is consumed by the next foreground change or auto-expires after a few
/// seconds; there is no unset API).
///
/// Failures are intentionally ignored (`let _ =`): a failed grant still leaves
/// the daemon's `AttachThreadInput` fallback (in
/// `registry::win32::set_foreground_window`) available, and erroring here
/// would break the user's hotkey flow for a non-fatal permission.
///
/// See (`docs/src/dev-guide/ipc-and-watchdog.md`) for the foreground-lock
/// diagnosis and why this is the documented PowerToys pattern.
fn grant_foreground_permission() {
    // ASFW_ANY == (DWORD)-1 == 0xFFFFFFFF — any thread may take the foreground.
    let _ = unsafe { AllowSetForegroundWindow(u32::MAX) };
}

/// Send a command to the daemon and print a success message on Ok.
///
/// A shared helper used by `cmd_stop`, `cmd_config_reload`, and every
/// dispatch command. Before sending, it grants the daemon one-shot foreground
/// activation permission (see [`grant_foreground_permission`]) so the
/// daemon's `SetForegroundWindow` calls aren't blocked by the Windows
/// foreground lock. Handles the three response variants:
/// [`SocketResponse::Ok`], [`SocketResponse::Error`], and
/// [`SocketResponse::Data`].
fn send_command(msg: SocketMessage, success_msg: &str) -> Result<(), String> {
    grant_foreground_permission();

    let response =
        transport::send_message(&msg).map_err(|e| format!("failed to send command: {e}"))?;

    match response {
        SocketResponse::Ok => {
            println!("flow: {success_msg}");
            Ok(())
        }
        SocketResponse::Error { message } => Err(format!("daemon error: {message}")),
        SocketResponse::Data { .. } => {
            println!("flow: {success_msg}");
            Ok(())
        }
    }
}

/// Resolve the editor command for opening config files.
///
/// Checks environment variables in order:
/// 1. `EDITOR` — the user's preferred editor.
/// 2. `VISUAL` — an alternative editor variable (common in Unix-like shells).
/// 3. `notepad.exe` — the Windows default.
///
/// # Errors
///
/// Returns an error string only if all three resolution paths fail (which
/// should never happen since `notepad.exe` is always available on Windows).
fn resolve_editor() -> Result<String, String> {
    if let Ok(editor) = std::env::var("EDITOR")
        && !editor.is_empty()
    {
        return Ok(editor);
    }

    if let Ok(editor) = std::env::var("VISUAL")
        && !editor.is_empty()
    {
        return Ok(editor);
    }

    // Windows default — always available.
    Ok("notepad.exe".to_string())
}

/// Spawn the daemon executable as a background process.
///
/// Uses `CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW` on native Windows so
/// the daemon runs fully detached from the terminal. No explicit `Stdio` is
/// set so that Rust's `Command::spawn()` calls `CreateProcessW` with
/// `bInheritHandles = FALSE` — this prevents the daemon from inheriting the
/// parent's kernel handles (e.g., stdout/stderr pipes created by test
/// harnesses like `assert_cmd`), which would otherwise keep those pipes open
/// after the parent exits.
///
/// Falls back to a plain `spawn()` when the detached spawn fails (e.g., under
/// WSL interop).
fn spawn_daemon(log_file_override: Option<&str>) -> Result<(), String> {
    let exe = find_daemon_exe()?;

    // CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW
    const DETACHED: u32 = 0x00000200 | 0x08000000;

    // Try detached spawn first (native Windows), fall back to plain spawn (WSL).
    // Both paths forward `--log-file` when provided.
    let child = daemon_command(&exe, log_file_override)
        .creation_flags(DETACHED)
        .spawn()
        .or_else(|_| daemon_command(&exe, log_file_override).spawn())
        .map_err(|e| format!("failed to spawn daemon ({}): {e}", exe.display()))?;

    // Explicitly drop the Child handle so we don't wait on the process.
    // The daemon runs independently in the background.
    drop(child);

    Ok(())
}

/// Build the daemon [`Command`] with any `--log-file` override applied.
///
/// Factored out so [`spawn_daemon`] can construct an identical command for
/// both the native detached spawn and the WSL fallback spawn — the
/// `--log-file` argument must be present on both paths for the override to
/// take effect regardless of which spawn path succeeds.
///
/// The config directory is NOT passed here; it is propagated to the daemon
/// via the inherited `FLOW_CONFIG_DIR` environment variable (see [`cmd_start`]).
fn daemon_command(exe: &std::path::Path, log_file_override: Option<&str>) -> Command {
    let mut cmd = Command::new(exe);
    if let Some(path) = log_file_override {
        cmd.arg("--log-file").arg(path);
    }
    cmd
}

/// Locate the `flowd.exe` binary next to the current executable.
fn find_daemon_exe() -> Result<std::path::PathBuf, String> {
    let current_exe =
        std::env::current_exe().map_err(|e| format!("cannot determine current executable: {e}"))?;

    let dir = current_exe
        .parent()
        .ok_or_else(|| "cannot determine executable directory".to_string())?;

    let daemon = dir.join("flowd.exe");
    if daemon.exists() {
        return Ok(daemon);
    }

    Err(format!("daemon binary not found at {}", daemon.display()))
}

/// Wait for the daemon to finish initialization by polling the named pipe.
///
/// Polls [`transport::is_daemon_running`] (which connects and immediately
/// drops the handle) until the daemon has created the pipe and entered its
/// accept loop, or the timeout expires.
fn wait_for_daemon() -> Result<(), String> {
    let deadline = std::time::Instant::now() + DAEMON_START_TIMEOUT;
    loop {
        if transport::is_daemon_running() {
            return Ok(());
        }
        if std::time::Instant::now() >= deadline {
            return Err("timed out waiting for daemon to start".into());
        }
        std::thread::sleep(Duration::from_millis(200));
    }
}

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

    use clap::Parser;

    // --- Win32 foreground-permission helper ---

    #[test]
    fn grant_foreground_permission_does_not_panic() {
        // Smoke test: the helper wraps an unsafe Win32 call that returns a
        // result code and never panics. End-to-end effectiveness (the daemon's
        // `SetForegroundWindow` now succeeds) is validated manually by
        // dispatching focus with the daemon running. This test guards against
        // future changes that alter the call path or the ASFW_ANY constant in a
        // way that breaks compilation of this path.
        grant_foreground_permission();
    }

    // --- Positive: each subcommand parses correctly ---

    #[test]
    fn parse_start() {
        let cli = Cli::try_parse_from(["flow", "start"]).unwrap();
        assert!(matches!(
            cli.command,
            Commands::Start {
                config: None,
                log_file: None,
                ahk: false
            }
        ));
    }

    #[test]
    fn parse_start_with_config_flag() {
        let cli = Cli::try_parse_from(["flow", "start", "--config", "C:\\custom\\flow"]).unwrap();
        match cli.command {
            Commands::Start {
                config: Some(ref c),
                ..
            } => {
                assert_eq!(c, "C:\\custom\\flow");
            }
            other => panic!("expected Start with --config, got: {other:?}"),
        }
    }

    #[test]
    fn parse_start_without_config_flag() {
        let cli = Cli::try_parse_from(["flow", "start"]).unwrap();
        match cli.command {
            Commands::Start { config: None, .. } => {}
            other => panic!("expected Start with no --config, got: {other:?}"),
        }
    }

    #[test]
    fn parse_start_with_log_file_flag() {
        let cli =
            Cli::try_parse_from(["flow", "start", "--log-file", "C:\\tmp\\debug.log"]).unwrap();
        match cli.command {
            Commands::Start {
                log_file: Some(ref p),
                ..
            } => {
                assert_eq!(p, "C:\\tmp\\debug.log");
            }
            other => panic!("expected Start with --log-file, got: {other:?}"),
        }
    }

    #[test]
    fn parse_start_with_config_and_log_file_flags() {
        let cli = Cli::try_parse_from([
            "flow",
            "start",
            "--config",
            "C:\\custom\\flow",
            "--log-file",
            "C:\\tmp\\debug.log",
        ])
        .unwrap();
        match cli.command {
            Commands::Start {
                config: Some(ref c),
                log_file: Some(ref p),
                ahk: false,
            } => {
                assert_eq!(c, "C:\\custom\\flow");
                assert_eq!(p, "C:\\tmp\\debug.log");
            }
            other => panic!("expected Start with both flags, got: {other:?}"),
        }
    }

    #[test]
    fn parse_start_with_ahk_config_and_log_file_combined() {
        // Composition lock: all three Start flags must coexist on one command
        // line without ordering sensitivity. Each flag is independently tested
        // above; this pins that the parser does not reject the combination.
        let cli = Cli::try_parse_from([
            "flow",
            "start",
            "--ahk",
            "--config",
            "C:\\custom\\flow",
            "--log-file",
            "C:\\tmp\\debug.log",
        ])
        .unwrap();
        match cli.command {
            Commands::Start {
                ahk: true,
                config: Some(ref c),
                log_file: Some(ref p),
            } => {
                assert_eq!(c, "C:\\custom\\flow");
                assert_eq!(p, "C:\\tmp\\debug.log");
            }
            other => panic!("expected Start with all three flags, got: {other:?}"),
        }
    }

    #[test]
    fn parse_stop() {
        let cli = Cli::try_parse_from(["flow", "stop"]).unwrap();
        assert!(matches!(cli.command, Commands::Stop { ahk: false }));
    }

    #[test]
    fn parse_start_with_ahk_flag() {
        let cli = Cli::try_parse_from(["flow", "start", "--ahk"]).unwrap();
        match cli.command {
            Commands::Start {
                ahk: true,
                config: None,
                log_file: None,
            } => {}
            other => panic!("expected Start {{ ahk: true, .. }}, got: {other:?}"),
        }
    }

    #[test]
    fn parse_stop_with_ahk_flag() {
        let cli = Cli::try_parse_from(["flow", "stop", "--ahk"]).unwrap();
        assert!(matches!(cli.command, Commands::Stop { ahk: true }));
    }

    #[test]
    fn parse_start_positional_arg_fails() {
        // Negative: `start` takes no positional args (only --config/--log-file/--ahk).
        let result = Cli::try_parse_from(["flow", "start", "unexpected"]);
        assert!(
            result.is_err(),
            "'flow start' with a positional arg should fail"
        );
    }

    #[test]
    fn parse_enable_autostart() {
        let cli = Cli::try_parse_from(["flow", "enable-autostart"]).unwrap();
        match cli.command {
            Commands::EnableAutostart { ahk: false } => {}
            other => panic!("expected EnableAutostart {{ ahk: false }}, got: {other:?}"),
        }
    }

    #[test]
    fn parse_enable_autostart_ahk() {
        let cli = Cli::try_parse_from(["flow", "enable-autostart", "--ahk"]).unwrap();
        match cli.command {
            Commands::EnableAutostart { ahk: true } => {}
            other => panic!("expected EnableAutostart {{ ahk: true }}, got: {other:?}"),
        }
    }

    #[test]
    fn parse_enable_autostart_extra_arg_fails() {
        // Negative: enable-autostart takes only --ahk, no positionals.
        let result = Cli::try_parse_from(["flow", "enable-autostart", "bogus"]);
        assert!(
            result.is_err(),
            "'flow enable-autostart' with a positional arg should fail"
        );
    }

    #[test]
    fn parse_enable_autostart_unknown_flag_fails() {
        // Negative: only --ahk is accepted.
        let result = Cli::try_parse_from(["flow", "enable-autostart", "--bogus"]);
        assert!(result.is_err(), "unknown flag should fail");
    }

    #[test]
    fn parse_disable_autostart() {
        let cli = Cli::try_parse_from(["flow", "disable-autostart"]).unwrap();
        assert!(matches!(cli.command, Commands::DisableAutostart));
    }

    #[test]
    fn parse_disable_autostart_ahk_flag_fails() {
        // Negative: disable-autostart takes no flags (single shortcut — see
        // option (a) design). This pins that --ahk is NOT accepted here.
        let result = Cli::try_parse_from(["flow", "disable-autostart", "--ahk"]);
        assert!(
            result.is_err(),
            "'flow disable-autostart --ahk' should fail (no --ahk flag)"
        );
    }

    #[test]
    fn parse_disable_autostart_extra_arg_fails() {
        // Negative: disable-autostart takes no arguments at all.
        let result = Cli::try_parse_from(["flow", "disable-autostart", "bogus"]);
        assert!(
            result.is_err(),
            "'flow disable-autostart' with a positional arg should fail"
        );
    }

    #[test]
    fn parse_config_init() {
        let cli = Cli::try_parse_from(["flow", "config", "init"]).unwrap();
        match cli.command {
            Commands::Config {
                command: ConfigCommands::Init { ahk },
            } => {
                // --ahk defaults to false when omitted.
                assert!(!ahk, "--ahk should default to false");
            }
            other => panic!("expected Config::Init, got: {other:?}"),
        }
    }

    #[test]
    fn parse_config_init_ahk() {
        let cli = Cli::try_parse_from(["flow", "config", "init", "--ahk"]).unwrap();
        match cli.command {
            Commands::Config {
                command: ConfigCommands::Init { ahk },
            } => {
                assert!(ahk, "--ahk should set ahk to true");
            }
            other => panic!("expected Config::Init {{ ahk: true }}, got: {other:?}"),
        }
    }

    #[test]
    fn parse_config_reload() {
        let cli = Cli::try_parse_from(["flow", "config", "reload"]).unwrap();
        match cli.command {
            Commands::Config {
                command: ConfigCommands::Reload,
            } => {}
            other => panic!("expected Config::Reload, got: {other:?}"),
        }
    }

    #[test]
    fn parse_config_edit() {
        let cli = Cli::try_parse_from(["flow", "config", "edit"]).unwrap();
        match cli.command {
            Commands::Config {
                command: ConfigCommands::Edit,
            } => {}
            other => panic!("expected Config::Edit, got: {other:?}"),
        }
    }

    #[test]
    fn parse_config_path() {
        let cli = Cli::try_parse_from(["flow", "config", "path"]).unwrap();
        match cli.command {
            Commands::Config {
                command: ConfigCommands::Path,
            } => {}
            other => panic!("expected Config::Path, got: {other:?}"),
        }
    }

    #[test]
    fn parse_config_check() {
        let cli = Cli::try_parse_from(["flow", "config", "check"]).unwrap();
        match cli.command {
            Commands::Config {
                command: ConfigCommands::Check,
            } => {}
            other => panic!("expected Config::Check, got: {other:?}"),
        }
    }

    #[test]
    fn parse_query_all() {
        let cli = Cli::try_parse_from(["flow", "query", "all"]).unwrap();
        match cli.command {
            Commands::Query {
                command: QueryCommands::All,
            } => {}
            other => panic!("expected Query::All, got: {other:?}"),
        }
    }

    // --- Dispatch command parsing ---

    #[test]
    fn parse_dispatch_focus_left() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "focus", "left"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::Focus {
                        direction: FocusDirection::Left,
                    },
            } => {}
            other => panic!("expected Dispatch::Focus::Left, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_focus_right() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "focus", "right"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::Focus {
                        direction: FocusDirection::Right,
                    },
            } => {}
            other => panic!("expected Dispatch::Focus::Right, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_focus_up() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "focus", "up"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::Focus {
                        direction: FocusDirection::Up,
                    },
            } => {}
            other => panic!("expected Dispatch::Focus::Up, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_focus_down() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "focus", "down"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::Focus {
                        direction: FocusDirection::Down,
                    },
            } => {}
            other => panic!("expected Dispatch::Focus::Down, got: {other:?}"),
        }
    }

    // --- swap-column parsing ---

    #[test]
    fn parse_dispatch_swap_column_left() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "swap-column", "left"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::SwapColumn {
                        direction: HorizontalDirection::Left,
                    },
            } => {}
            other => panic!("expected Dispatch::SwapColumn::Left, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_swap_column_right() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "swap-column", "right"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::SwapColumn {
                        direction: HorizontalDirection::Right,
                    },
            } => {}
            other => panic!("expected Dispatch::SwapColumn::Right, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_swap_column_without_direction_fails() {
        // Negative: swap-column needs a direction subcommand.
        let result = Cli::try_parse_from(["flow", "dispatch", "swap-column"]);
        assert!(
            result.is_err(),
            "'flow dispatch swap-column' without a direction should fail"
        );
    }

    #[test]
    fn parse_dispatch_swap_column_vertical_fails() {
        // Negative: swap-column only accepts left/right (HorizontalDirection).
        let result = Cli::try_parse_from(["flow", "dispatch", "swap-column", "up"]);
        assert!(
            result.is_err(),
            "'swap-column up' should fail (only left/right)"
        );
    }

    // --- move-window parsing ---

    #[test]
    fn parse_dispatch_move_window_left() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "move-window", "left"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::MoveWindow {
                        direction: MoveDirection::Left,
                    },
            } => {}
            other => panic!("expected Dispatch::MoveWindow::Left, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_move_window_right() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "move-window", "right"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::MoveWindow {
                        direction: MoveDirection::Right,
                    },
            } => {}
            other => panic!("expected Dispatch::MoveWindow::Right, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_move_window_up() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "move-window", "up"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::MoveWindow {
                        direction: MoveDirection::Up,
                    },
            } => {}
            other => panic!("expected Dispatch::MoveWindow::Up, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_move_window_down() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "move-window", "down"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::MoveWindow {
                        direction: MoveDirection::Down,
                    },
            } => {}
            other => panic!("expected Dispatch::MoveWindow::Down, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_move_window_without_direction_fails() {
        // Negative: move-window needs a direction subcommand.
        let result = Cli::try_parse_from(["flow", "dispatch", "move-window"]);
        assert!(
            result.is_err(),
            "'flow dispatch move-window' without a direction should fail"
        );
    }

    // --- merge-column parsing ---

    #[test]
    fn parse_dispatch_merge_column_left() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "merge-column", "left"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::MergeColumn {
                        direction: HorizontalDirection::Left,
                    },
            } => {}
            other => panic!("expected Dispatch::MergeColumn::Left, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_merge_column_right() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "merge-column", "right"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::MergeColumn {
                        direction: HorizontalDirection::Right,
                    },
            } => {}
            other => panic!("expected Dispatch::MergeColumn::Right, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_merge_column_vertical_fails() {
        // Negative: merge-column only accepts left/right (HorizontalDirection).
        let result = Cli::try_parse_from(["flow", "dispatch", "merge-column", "up"]);
        assert!(
            result.is_err(),
            "'merge-column up' should fail (only left/right)"
        );
    }

    // --- promote parsing ---

    #[test]
    fn parse_dispatch_promote_left() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "promote", "left"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::Promote {
                        direction: HorizontalDirection::Left,
                    },
            } => {}
            other => panic!("expected Dispatch::Promote::Left, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_promote_right() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "promote", "right"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::Promote {
                        direction: HorizontalDirection::Right,
                    },
            } => {}
            other => panic!("expected Dispatch::Promote::Right, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_promote_vertical_fails() {
        // Negative: promote only accepts left/right (HorizontalDirection).
        let result = Cli::try_parse_from(["flow", "dispatch", "promote", "down"]);
        assert!(
            result.is_err(),
            "'promote down' should fail (only left/right)"
        );
    }

    #[test]
    fn parse_dispatch_without_subcommand_fails() {
        // Negative: `flow dispatch` without a subcommand should fail to parse
        // (clap requires a subcommand).
        let result = Cli::try_parse_from(["flow", "dispatch"]);
        assert!(
            result.is_err(),
            "'flow dispatch' without a subcommand should fail"
        );
    }

    #[test]
    fn parse_dispatch_focus_without_direction_fails() {
        // Negative: `flow dispatch focus` without a direction should fail.
        let result = Cli::try_parse_from(["flow", "dispatch", "focus"]);
        assert!(
            result.is_err(),
            "'flow dispatch focus' without a direction should fail"
        );
    }

    #[test]
    fn parse_dispatch_invalid_subcommand_fails() {
        // Negative: unknown dispatch subcommand should fail.
        let result = Cli::try_parse_from(["flow", "dispatch", "nonexistent"]);
        assert!(result.is_err(), "unknown dispatch subcommand should fail");
    }

    // --- Dispatch expand-column / shrink-column ---

    #[test]
    fn parse_dispatch_expand_column() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "expand-column"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command: DispatchCommands::ExpandColumn,
            } => {}
            other => panic!("expected Dispatch::ExpandColumn, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_shrink_column() {
        let cli = Cli::try_parse_from(["flow", "dispatch", "shrink-column"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command: DispatchCommands::ShrinkColumn,
            } => {}
            other => panic!("expected Dispatch::ShrinkColumn, got: {other:?}"),
        }
    }

    // --- Dispatch center ---
    //
    // `center` is the one variant whose explicit `#[command(name = "center")]`
    // attribute was *removed* in the kebab-case rename (clap derives the same
    // single-word name, so the override was redundant). This test pins that
    // derivation: if a future clap version or refactor changes the derived
    // name, this is the canary that fails.

    #[test]
    fn parse_dispatch_center() {
        // Positive: `flow dispatch center` parses to the Center variant.
        let cli = Cli::try_parse_from(["flow", "dispatch", "center"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command: DispatchCommands::Center,
            } => {}
            other => panic!("expected Dispatch::Center, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_close_window() {
        // Positive: `flow dispatch close-window` parses to the CloseWindow variant.
        let cli = Cli::try_parse_from(["flow", "dispatch", "close-window"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command: DispatchCommands::CloseWindow,
            } => {}
            other => panic!("expected Dispatch::CloseWindow, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_close_window_extra_arg_fails() {
        // Negative: close-window takes no arguments.
        let result = Cli::try_parse_from(["flow", "dispatch", "close-window", "extra"]);
        assert!(
            result.is_err(),
            "'flow dispatch close-window' with an extra arg should fail"
        );
    }

    // --- set-window parsing ---

    #[test]
    fn parse_dispatch_set_window_float() {
        // Positive: `flow dispatch set-window float` parses with mode = Float.
        let cli = Cli::try_parse_from(["flow", "dispatch", "set-window", "float"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::SetWindow {
                        mode: WindowMode::Float,
                    },
            } => {}
            other => panic!("expected Dispatch::SetWindow::Float, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_set_window_tile() {
        // Positive: `flow dispatch set-window tile` parses with mode = Tile.
        let cli = Cli::try_parse_from(["flow", "dispatch", "set-window", "tile"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::SetWindow {
                        mode: WindowMode::Tile,
                    },
            } => {}
            other => panic!("expected Dispatch::SetWindow::Tile, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_set_window_cycle() {
        // Positive: `flow dispatch set-window cycle` parses with mode = Cycle.
        let cli = Cli::try_parse_from(["flow", "dispatch", "set-window", "cycle"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command:
                    DispatchCommands::SetWindow {
                        mode: WindowMode::Cycle,
                    },
            } => {}
            other => panic!("expected Dispatch::SetWindow::Cycle, got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_set_window_without_mode_fails() {
        // Negative: set-window needs a mode subcommand.
        let result = Cli::try_parse_from(["flow", "dispatch", "set-window"]);
        assert!(
            result.is_err(),
            "'flow dispatch set-window' without a mode should fail"
        );
    }

    #[test]
    fn parse_dispatch_set_window_invalid_mode_fails() {
        // Negative: set-window only accepts float/tile/cycle.
        let result = Cli::try_parse_from(["flow", "dispatch", "set-window", "invalid"]);
        assert!(
            result.is_err(),
            "'flow dispatch set-window invalid' should fail"
        );
    }

    #[test]
    fn parse_dispatch_expand_column_extra_arg_fails() {
        // Negative: expand-column takes no arguments.
        let result = Cli::try_parse_from(["flow", "dispatch", "expand-column", "extra"]);
        assert!(
            result.is_err(),
            "'flow dispatch expand-column' with extra args should fail"
        );
    }

    #[test]
    fn parse_dispatch_shrink_column_extra_arg_fails() {
        // Negative: shrink-column takes no arguments — extra positional arg rejected.
        let result = Cli::try_parse_from(["flow", "dispatch", "shrink-column", "extra"]);
        assert!(
            result.is_err(),
            "'flow dispatch shrink-column' with extra args should fail"
        );
    }

    #[test]
    fn parse_dispatch_expand_column_multiple_extra_args_fails() {
        // Negative: expand-column rejects more than one extra argument.
        let result = Cli::try_parse_from(["flow", "dispatch", "expand-column", "extra1", "extra2"]);
        assert!(
            result.is_err(),
            "'flow dispatch expand-column' with multiple extra args should fail"
        );
    }

    #[test]
    fn parse_dispatch_shrink_column_multiple_extra_args_fails() {
        // Negative: shrink-column rejects more than one extra argument.
        let result = Cli::try_parse_from(["flow", "dispatch", "shrink-column", "extra1", "extra2"]);
        assert!(
            result.is_err(),
            "'flow dispatch shrink-column' with multiple extra args should fail"
        );
    }

    // --- switch-workspace / swap-workspace / move-to-workspace parsing ---

    #[test]
    fn parse_dispatch_switch_workspace() {
        // Positive: `flow dispatch switch-workspace 3` parses with workspace_id = 3.
        let cli = Cli::try_parse_from(["flow", "dispatch", "switch-workspace", "3"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command: DispatchCommands::SwitchWorkspace { workspace_id: 3 },
            } => {}
            other => panic!("expected Dispatch::SwitchWorkspace(3), got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_switch_workspace_without_id_fails() {
        // Negative: switch-workspace needs a workspace_id argument.
        let result = Cli::try_parse_from(["flow", "dispatch", "switch-workspace"]);
        assert!(
            result.is_err(),
            "'flow dispatch switch-workspace' without an id should fail"
        );
    }

    #[test]
    fn parse_dispatch_switch_workspace_zero() {
        // Positive: workspace_id = 0 is accepted by the parser (boundary value).
        // The daemon decides whether 0 is a valid workspace; the CLI does not.
        let cli = Cli::try_parse_from(["flow", "dispatch", "switch-workspace", "0"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command: DispatchCommands::SwitchWorkspace { workspace_id: 0 },
            } => {}
            other => panic!("expected Dispatch::SwitchWorkspace(0), got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_swap_workspace() {
        // Positive: `flow dispatch swap-workspace 7` parses with workspace_id = 7.
        let cli = Cli::try_parse_from(["flow", "dispatch", "swap-workspace", "7"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command: DispatchCommands::SwapWorkspace { workspace_id: 7 },
            } => {}
            other => panic!("expected Dispatch::SwapWorkspace(7), got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_swap_workspace_without_id_fails() {
        // Negative: swap-workspace needs a workspace_id argument.
        let result = Cli::try_parse_from(["flow", "dispatch", "swap-workspace"]);
        assert!(
            result.is_err(),
            "'flow dispatch swap-workspace' without an id should fail"
        );
    }

    #[test]
    fn parse_dispatch_move_to_workspace() {
        // Positive: `flow dispatch move-to-workspace 11` parses with workspace_id = 11.
        // The CLI command name stays `move-to-workspace` (short form) even though
        // the underlying Rust variant is `MoveWindowToWorkspace`.
        let cli = Cli::try_parse_from(["flow", "dispatch", "move-to-workspace", "11"]).unwrap();
        match cli.command {
            Commands::Dispatch {
                command: DispatchCommands::MoveWindowToWorkspace { workspace_id: 11 },
            } => {}
            other => panic!("expected Dispatch::MoveWindowToWorkspace(11), got: {other:?}"),
        }
    }

    #[test]
    fn parse_dispatch_move_to_workspace_without_id_fails() {
        // Negative: move-to-workspace needs a workspace_id argument.
        let result = Cli::try_parse_from(["flow", "dispatch", "move-to-workspace"]);
        assert!(
            result.is_err(),
            "'flow dispatch move-to-workspace' without an id should fail"
        );
    }

    #[test]
    fn parse_dispatch_workspace_command_rejects_non_numeric_id() {
        // Negative: workspace_id must be a u32; a non-numeric token is rejected.
        let result = Cli::try_parse_from(["flow", "dispatch", "switch-workspace", "abc"]);
        assert!(
            result.is_err(),
            "non-numeric workspace_id should be rejected"
        );
    }

    // --- Negative: invalid invocations ---

    #[test]
    fn parse_no_subcommand_fails() {
        // Negative: no subcommand should fail to parse
        let result = Cli::try_parse_from(["flow"]);
        assert!(result.is_err(), "parsing with no subcommand should fail");
    }

    #[test]
    fn parse_invalid_subcommand_fails() {
        // Negative: unknown subcommand should fail
        let result = Cli::try_parse_from(["flow", "nonexistent"]);
        assert!(result.is_err(), "unknown subcommand should fail");
    }

    #[test]
    fn parse_extra_arg_fails() {
        // Negative: extra argument to a subcommand that takes none should fail
        let result = Cli::try_parse_from(["flow", "stop", "unexpected"]);
        assert!(result.is_err(), "extra argument should fail");
    }

    #[test]
    fn parse_empty_args_fails() {
        // Negative: empty argument list should fail
        let result = Cli::try_parse_from([""]);
        assert!(result.is_err(), "empty args should fail");
    }

    // --- Negative: old flat commands should no longer parse ---

    #[test]
    fn parse_old_reload_config_fails() {
        // Negative: the old `flow reload-config` flat command no longer exists
        let result = Cli::try_parse_from(["flow", "reload-config"]);
        assert!(
            result.is_err(),
            "old 'reload-config' command should no longer parse"
        );
    }

    #[test]
    fn parse_old_check_config_fails() {
        // Negative: the old `flow check-config` flat command no longer exists
        let result = Cli::try_parse_from(["flow", "check-config"]);
        assert!(
            result.is_err(),
            "old 'check-config' command should no longer parse"
        );
    }

    // --- Negative: old squished dispatch subcommands should no longer parse ---
    //
    // The `flow dispatch <sub>` surface was renamed from squished-lowercase
    // (e.g. `swapcolumn`) to kebab-case (`swap-column`). Existing user scripts
    // and keybindings that still spell the old form must now be rejected by
    // clap rather than silently mis-route. Each case below is the OLD form of
    // a subcommand that has a sibling positive test above proving the NEW
    // kebab form parses; together they pin both ends of the rename.
    // `center` is intentionally absent here — it was never renamed.

    #[test]
    fn parse_old_squished_dispatch_subcommands_fail() {
        let old_forms = [
            "swapcolumn",
            "movewindow",
            "expandcolumn",
            "shrinkcolumn",
            "closewindow",
            "setwindow",
            "switchworkspace",
            "swapworkspace",
            "movetoworkspace",
        ];
        for old in old_forms {
            let result = Cli::try_parse_from(["flow", "dispatch", old]);
            assert!(
                result.is_err(),
                "old squished dispatch subcommand '{old}' should no longer parse"
            );
        }
    }

    // --- Negative: invalid config subcommand ---

    #[test]
    fn parse_config_invalid_subcommand_fails() {
        let result = Cli::try_parse_from(["flow", "config", "nonexistent"]);
        assert!(result.is_err(), "unknown config subcommand should fail");
    }

    // --- Negative: config subcommand with extra args ---

    #[test]
    fn parse_config_subcommand_extra_arg_fails() {
        let result = Cli::try_parse_from(["flow", "config", "path", "unexpected"]);
        assert!(
            result.is_err(),
            "extra argument to config subcommand should fail"
        );
    }

    // --- DAEMON_START_TIMEOUT wiring tests ---

    // Positive: DAEMON_START_TIMEOUT is a reasonable bounded value
    #[test]
    fn daemon_start_timeout_is_reasonable() {
        assert!(
            DAEMON_START_TIMEOUT.as_secs() > 0,
            "DAEMON_START_TIMEOUT must be > 0"
        );
        assert!(
            DAEMON_START_TIMEOUT.as_secs() <= 30,
            "DAEMON_START_TIMEOUT must be <= 30s (user shouldn't wait longer)"
        );
    }

    // Negative: DAEMON_START_TIMEOUT is not zero (would mean no wait)
    #[test]
    fn daemon_start_timeout_is_not_zero() {
        assert_ne!(
            DAEMON_START_TIMEOUT,
            Duration::ZERO,
            "zero timeout would skip waiting entirely"
        );
    }

    // Positive: wait_for_daemon() correctly wraps transport::wait_for_pipe errors.
    // Verifies the error-formatting wrapper in wait_for_daemon().
    // It cannot call wait_for_daemon() directly (would block on pipe),
    // but we verify the function exists and is callable by confirming it
    // compiles and its signature returns Result<(), String>.
    #[test]
    fn wait_for_daemon_maps_not_found_error() {
        let _: fn() -> Result<(), String> = wait_for_daemon;
    }

    // --- resolve_editor tests ---

    #[test]
    fn resolve_editor_returns_string() {
        let result = resolve_editor();
        assert!(result.is_ok(), "resolve_editor should always return Ok");
        let editor = result.unwrap();
        assert!(!editor.is_empty(), "editor command should not be empty");
    }
}