narwhal-commands 2.3.0

Stateless command and helper modules for narwhal: completion, export, wizard, snippets, DDL, EXPLAIN, cell edit, statement extraction.
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
/// Parsed flag bag for [`Command::Export`].
///
/// `compression` is `Some` only when the user explicitly passed
/// `--compression <codec>`; the dispatch layer falls back to the
/// format's default codec when it sees `None`. `no_truncate` is the
/// boolean form of `--no-truncate`.
///
/// We keep this as a small typed struct (rather than `Vec<String>`)
/// because the parser already validates the codec token, and the
/// dispatch layer would otherwise have to reparse the strings.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ExportArgs {
    pub compression: Option<crate::export::ParquetCompression>,
    pub no_truncate: bool,
}

/// Selector for [`Command::DumpSchema`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DumpTarget {
    /// Dump the table currently shown in the result pane (`TableDetail`).
    Current,
    /// Dump every table the active session knows about.
    All,
    /// Dump the named table (resolved through the active session).
    Named(String),
}

/// Output format accepted by [`Command::DiagramExport`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagramFormat {
    /// Mermaid `erDiagram` source (paste into mermaid.live).
    Mermaid,
    /// Graphviz `dot` source (`dot -Tsvg` to render).
    Dot,
}

impl DiagramFormat {
    pub fn from_token(token: &str) -> Option<Self> {
        match token.to_ascii_lowercase().as_str() {
            "mermaid" | "mmd" | "mer" => Some(Self::Mermaid),
            "dot" | "gv" | "graphviz" => Some(Self::Dot),
            _ => None,
        }
    }

    /// File extension used when the user omits one in `:diagram export`.
    pub const fn default_extension(self) -> &'static str {
        match self {
            Self::Mermaid => "mmd",
            Self::Dot => "dot",
        }
    }

    /// Human-readable label for status messages.
    pub const fn label(self) -> &'static str {
        match self {
            Self::Mermaid => "mermaid",
            Self::Dot => "dot",
        }
    }
}

/// Isolation levels accepted by `:begin`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationArg {
    ReadUncommitted,
    ReadCommitted,
    RepeatableRead,
    Serializable,
}

impl IsolationArg {
    pub fn parse(token: &str) -> Option<Self> {
        match token
            .to_ascii_lowercase()
            .replace([' ', '_', '-'], "")
            .as_str()
        {
            "readuncommitted" | "uncommitted" | "ru" => Some(Self::ReadUncommitted),
            "readcommitted" | "committed" | "rc" => Some(Self::ReadCommitted),
            "repeatableread" | "repeatable" | "rr" => Some(Self::RepeatableRead),
            "serializable" | "s" => Some(Self::Serializable),
            _ => None,
        }
    }
}

/// Top-level `:`-line commands accepted by the application.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
    Quit,
    Open(String),
    Close,
    Refresh,
    Run,
    RunAll,
    Stream,
    StreamAll,
    Cancel,
    Clear,
    Explain,
    Export {
        format: String,
        path: String,
        /// parsed options for the chosen format (parquet
        /// `--compression`, markdown `--no-truncate`, etc). Empty
        /// for csv/json/tsv/table/insert, populated for parquet/md.
        options: ExportArgs,
    },
    DumpSchema {
        target: DumpTarget,
    },
    /// Export an ER diagram of the active connection's schema as
    /// Mermaid (`erDiagram`) or Graphviz (`dot`). When `path` is `None`
    /// the rendered string is copied to the system clipboard; otherwise
    /// it is written to disk.
    ///
    /// `table` restricts the diagram to that table and its 1-hop FK
    /// neighbours; `schema` restricts to a single schema.
    DiagramExport {
        format: DiagramFormat,
        path: Option<String>,
        table: Option<String>,
        schema: Option<String>,
    },
    /// Open the in-TUI diagram modal in *Focused* mode, centred on the
    /// given table. The table token may be `name` or `schema.name`.
    DiagramFocus(String),
    /// Open the in-TUI diagram modal in *Impact* mode (reverse-FK
    /// closure) for the given table.
    DiagramImpact(String),
    NewTab,
    CloseTab,
    NextTab,
    PrevTab,
    Add,
    /// Pretty-print the SQL statement under the cursor in place. Uses
    /// the active session's dialect when one is open, otherwise the
    /// generic profile.
    Format,
    /// Pretty-print every statement in the editor buffer.
    FormatAll,
    /// Pre-fill the connection wizard from a connection URL
    /// (`:url postgres://user:pass@host/db`). The user can still tweak
    /// the form before saving.
    Url(String),
    /// Test connectivity. With no argument, pings the active session;
    /// with an argument, opens a transient session (looking the name up
    /// in `connections.toml` or parsing the argument as a URL) and
    /// closes it immediately.
    Test(Option<String>),
    /// Open the connection wizard pre-filled from an existing saved
    /// connection (`:edit <name>`). Committing the wizard updates the
    /// entry in place and rewrites its keyring secret.
    Edit(String),
    Begin(Option<IsolationArg>),
    /// Re-run the most recent table preview with the next page of rows.
    NextPage,
    /// Re-run the most recent table preview with the previous page.
    PrevPage,
    /// Set the page size used by [`Command::NextPage`] / [`Command::PrevPage`]
    /// and the initial sidebar preview.
    PageSize(usize),
    Commit,
    Rollback,
    Savepoint(String),
    Release(String),
    RollbackTo(String),
    /// Remove a saved connection by name (also clears its keyring entry).
    Remove(String),
    /// Forget the keyring password for a saved connection by name; the
    /// connection itself stays in `connections.toml`.
    Forget(String),
    /// Load a Lua plugin from disk (`:plug-load path/to/foo.lua`).
    PluginLoad(String),
    /// List loaded plugins and the commands they expose.
    PluginList,
    /// Open the Ctrl+R history modal. With `Some(pattern)` pre-fills
    /// the filter.
    History(Option<String>),
    /// L36 #1: open the staged-mutation preview modal. Discoverable
    /// counterpart to the `Ctrl-P` chord for users who live in the
    /// command line.
    Pending,
    /// flush every pending mutation inside one transaction.
    /// Equivalent to `Ctrl-S` while the pending preview is open.
    Submit,
    /// throw away every pending mutation without writing.
    /// Equivalent to `Ctrl-X` inside the preview.
    Revert,
    Help(Option<String>),
    /// Substitute command: `:s/old/new/[g][c]` or `:%s/old/new/[g][c]`.
    Substitute {
        range: SubstituteRange,
        pattern: String,
        replacement: String,
        global: bool,
        confirm: bool,
    },
    /// Clear search highlighting (`:nohlsearch`).
    NoHlSearch,
    /// Save the current editor buffer as a named snippet (`:save <name>`).
    SaveSnippet {
        name: String,
    },
    /// Load a named snippet into a new editor tab (`:load <name>`).
    LoadSnippet {
        name: String,
    },
    /// Delete a named snippet (`:rm-snippet <name>`).
    RemoveSnippet {
        name: String,
    },
    /// Open the snippets modal (`:snippets`).
    ListSnippets,
    /// open the fuzzy schema navigator (`:goto` / `:g` / Ctrl-N).
    /// Lists every table/view across all loaded schemas, picks one
    /// via fuzzy match, inserts `<schema>.<table>` at the cursor on
    /// confirm.
    Goto,
    /// In-app settings editor (`:settings` / `:set`). Opens the
    /// modal that drives editor mode, mouse mode, theme,
    /// keybinding preset, etc. Commits to `settings.toml` on save.
    Settings,
    /// Quick editor-mode switch (`:mode vim|basic|emacs`). Bypasses
    /// the settings modal; persists to disk via the same code path.
    Mode(String),
    /// set the result-pane filter (`:filter <expr>`) or
    /// clear it (`:filter clear`). Same expression that the inline
    /// `f` prompt accepts; commits immediately.
    Filter(Option<String>),
    /// toggle a sort on a 1-based column number
    /// (`:sort 3`) or clear the active sort (`:sort clear`).
    Sort(SortArg),
    /// emit ALTER TABLE migration SQL between two tables in
    /// the active connection. Format: `:diff-schema a.tbl1 b.tbl2`.
    /// The result lands in a fresh editor tab so the user can review
    /// before executing.
    DiffSchema {
        left: String,
        right: String,
    },
    /// full-schema diff between two **connections**
    /// (`:schema-diff source target`). Opens both transiently,
    /// introspects every user table, runs `narwhal-schema-diff`,
    /// dumps the emitted DDL into a fresh editor tab. Optional
    /// flags pick the dialect, narrow the scope, or rewrite target
    /// schema names. Note this is distinct from `:diff-schema`,
    /// which is single-connection two-table.
    SchemaDiff {
        /// Source connection (desired state).
        source: String,
        /// Target connection (will be migrated).
        target: String,
        /// Override the auto-picked dialect; `None` uses the
        /// source connection's driver name.
        dialect: Option<String>,
        /// Restrict the diff to one schema (both sides).
        schema: Option<String>,
        /// Restrict the diff to one table.
        table: Option<String>,
        /// `(source, target)` schema renames applied to the
        /// target-side introspection before diffing.
        schema_map: Vec<(String, String)>,
    },
    /// run the lint rule set over the active buffer and
    /// dump findings to a fresh tab. `:lint` reuses the active tab's
    /// content; no argument needed.
    Lint,
    /// toggle the inline ASCII chart pane over the active
    /// result. `:chart bar|line|sparkline` activates the pane;
    /// `:chart off` (or `:chart none`) removes it. Optional flags:
    /// `--x col`, `--y col`, `--col col` (sparkline alias), `--title T`.
    Chart(ChartArg),
    /// toggle the inline pivot-table pane over the active
    /// result. `:pivot rows=col[,col..] [cols=col] [value=col]
    /// [agg=count|sum|avg|min|max]` activates; `:pivot off` removes it.
    Pivot(PivotArg),
    /// insert a built-in SQL template at the cursor.
    /// `:tpl sel` etc.; `:tpl` (no arg) shows the available names.
    Template(Option<String>),
    Unknown(String),
    Empty,
}

/// Argument to [`Command::Chart`]. The parser turns the command-line
/// flags into a structured payload so the dispatch layer can wire the
/// chart config in one step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChartArg {
    /// Activate the chart pane with the given kind and overrides.
    On {
        /// Token the user typed: `bar`, `line`, or `sparkline`.
        kind: ChartKindArg,
        /// `--title T` override; rendered in the chart's title bar.
        title: Option<String>,
        /// `--x col` override; ignored for sparkline.
        x_col: Option<String>,
        /// `--y col` (or `--col col` for sparkline) override.
        y_col: Option<String>,
    },
    /// `:chart off` / `:chart none` — dismiss the chart pane.
    Off,
}

/// Chart kind token parsed by [`Command::Chart`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChartKindArg {
    Bar,
    Line,
    Sparkline,
}

impl ChartKindArg {
    pub fn from_token(token: &str) -> Option<Self> {
        match token.to_ascii_lowercase().as_str() {
            "bar" => Some(Self::Bar),
            "line" => Some(Self::Line),
            "sparkline" | "spark" => Some(Self::Sparkline),
            _ => None,
        }
    }
}

/// Argument to [`Command::Pivot`]. The parser turns the
/// `key=value` tokens into a structured payload so the dispatch
/// layer can wire the pivot config in one step.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PivotArg {
    /// Activate the pivot pane with the given config.
    On {
        /// Row-dimension columns (comma-separated on the command line).
        rows: Vec<String>,
        /// Optional column-dimension; when `None` the pivot is a
        /// single collapsed column.
        cols: Option<String>,
        /// Optional value column; required for sum / avg / min / max.
        value: Option<String>,
        /// Aggregator kind token; the dispatch layer maps to
        /// `narwhal_pivot::AggKind`.
        agg: PivotAggArg,
    },
    /// `:pivot off` — dismiss the pivot pane.
    Off,
}

/// Aggregator token parsed by [`Command::Pivot`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PivotAggArg {
    Count,
    Sum,
    Avg,
    Min,
    Max,
}

impl PivotAggArg {
    pub fn from_token(token: &str) -> Option<Self> {
        match token.to_ascii_lowercase().as_str() {
            "count" | "cnt" | "n" => Some(Self::Count),
            "sum" | "total" => Some(Self::Sum),
            "avg" | "mean" | "average" => Some(Self::Avg),
            "min" | "minimum" => Some(Self::Min),
            "max" | "maximum" => Some(Self::Max),
            _ => None,
        }
    }
}

/// Argument to [`Command::Sort`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SortArg {
    /// 1-based column number. Toggle ascending → descending → cleared.
    Column(usize),
    /// `:sort clear` — drop the active sort.
    Clear,
}

/// Scope of a substitute command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubstituteRange {
    /// Replace on the current line only (`:s/…`).
    CurrentLine,
    /// Replace across the entire buffer (`:%s/…`).
    WholeBuffer,
}

/// Every token the parser accepts as a built-in `:`-line command head.
///
/// Plugins that try to register one of these names are rejected at
/// load time so the user isn't left wondering why their `:run`
/// override never runs (the parser would always match the built-in
/// first).
///
/// Keep this list in sync with the `match head` arms below in [`parse`].
pub const BUILTIN_COMMAND_NAMES: &[&str] = &[
    "q",
    "quit",
    "exit",
    "open",
    "o",
    "close",
    "refresh",
    "r",
    "run",
    "run-all",
    "runall",
    "stream",
    "stream-all",
    "streamall",
    "cancel",
    "clear",
    "explain",
    "export",
    "dump-schema",
    "dumpschema",
    "diagram",
    "diag",
    "schema-diff",
    "schemadiff",
    "chart",
    "add",
    "format",
    "fmt",
    "format-all",
    "fmtall",
    "url",
    "test",
    "edit",
    "next",
    "next-page",
    "npage",
    "prev",
    "prev-page",
    "ppage",
    "page-size",
    "pagesize",
    "begin",
    "start",
    "commit",
    "rollback",
    "abort",
    "savepoint",
    "sp",
    "release",
    "rollback-to",
    "rollbackto",
    "remove",
    "rm",
    "forget",
    "plug-load",
    "plugload",
    "plug",
    "plug-list",
    "pluglist",
    "plugins",
    "history",
    "new",
    "tabnew",
    "tabclose",
    "tc",
    "tabnext",
    "tn",
    "tabprev",
    "tp",
    "tabprevious",
    "help",
    "h",
    "nohlsearch",
    "noh",
    "save",
    "load",
    "rm-snippet",
    "rmsnippet",
    "snippets",
    "pivot",
    "settings",
    "set",
    "mode",
];

/// Short descriptions for built-in commands, looked up by `:help <name>`.
///
/// Each entry maps a primary token to a one-line human-readable summary.
/// Aliases (e.g. `"o"` for `"open"`) are not listed here — `:help o`
/// resolves through the parser to `Help(Some("o"))` and the core maps
/// aliases back to the primary key before consulting this table.
pub const BUILTIN_COMMAND_DESCRIPTIONS: &[(&str, &str)] = &[
    ("quit", "quit narwhal (also :q, :exit)"),
    ("open", "open a saved connection by name or URL (also :o)"),
    ("close", "close the current database connection"),
    (
        "refresh",
        "re-fetch the schema tree for the active connection",
    ),
    ("run", "execute the SQL statement under the cursor"),
    (
        "run-all",
        "execute every statement in the editor buffer (also :runall)",
    ),
    (
        "stream",
        "stream the SQL statement under the cursor (row by row)",
    ),
    (
        "stream-all",
        "stream every statement in the editor buffer (also :streamall)",
    ),
    ("cancel", "cancel the currently running query"),
    ("clear", "erase the editor buffer and its result"),
    (
        "explain",
        "run EXPLAIN ANALYZE on the current statement (postgres)",
    ),
    (
        "export",
        "export the current result to a file (:export csv|json|tsv|insert|parquet|markdown <path>)",
    ),
    (
        "dump-schema",
        "write CREATE TABLE DDL into the editor (:dump-schema [name|all])",
    ),
    (
        "diagram",
        "export an ER diagram (:diagram export mermaid|dot [path] [--table T] [--schema S])",
    ),
    (
        "schema-diff",
        "full-schema diff between two connections (:schema-diff src tgt [--dialect ..] [--schema ..] [--table ..] [--schema-map src=tgt])",
    ),
    (
        "chart",
        "render an inline ASCII chart over the active result (:chart bar|line|sparkline [--x col] [--y col] [--title T]; :chart off)",
    ),
    ("add", "open the connection wizard to save a new connection"),
    (
        "format",
        "pretty-print the SQL under the cursor (also :fmt)",
    ),
    (
        "format-all",
        "pretty-print every statement in the buffer (also :fmtall)",
    ),
    (
        "url",
        "open the wizard pre-filled from a DSN (:url postgres://user:pw@host/db)",
    ),
    (
        "test",
        "test connectivity (:test [name|url]); no arg pings the active session",
    ),
    (
        "edit",
        "edit a saved connection in the wizard (:edit <name>)",
    ),
    (
        "next-page",
        "show the next page of the current table preview (also :next)",
    ),
    (
        "prev-page",
        "show the previous page of the current table preview (also :prev)",
    ),
    (
        "page-size",
        "set the number of rows per page for previews (:page-size N)",
    ),
    (
        "begin",
        "start a transaction with an optional isolation level",
    ),
    ("commit", "commit the open transaction"),
    ("rollback", "roll back the open transaction (also :abort)"),
    (
        "savepoint",
        "create a savepoint inside the open transaction (also :sp)",
    ),
    ("release", "release a previously created savepoint"),
    (
        "rollback-to",
        "roll back to a previously created savepoint (also :rollbackto)",
    ),
    ("remove", "remove a saved connection by name (also :rm)"),
    (
        "forget",
        "delete the stored password for a saved connection",
    ),
    (
        "plug-load",
        "load a Lua plugin from disk (:plug-load <path>)",
    ),
    (
        "plug-list",
        "list loaded plugins and the commands they expose",
    ),
    ("history", "open the query history modal (also Ctrl+R)"),
    ("new", "open a new editor tab (also :tabnew)"),
    ("tabclose", "close the current editor tab (also :tc)"),
    ("tabnext", "switch to the next editor tab (also :tn)"),
    ("tabprev", "switch to the previous editor tab (also :tp)"),
    (
        "help",
        "show help; :help <command> for details on a specific command",
    ),
    (
        "nohlsearch",
        "clear search highlighting in the editor (also :noh)",
    ),
    (
        "save",
        "save the current editor buffer as a named snippet (:save <name>)",
    ),
    (
        "load",
        "load a named snippet into a new editor tab (:load <name>)",
    ),
    ("rm-snippet", "delete a named snippet (:rm-snippet <name>)"),
    (
        "snippets",
        "open the snippets modal to browse and load saved queries",
    ),
    (
        "pivot",
        "render an inline pivot table over the active result (:pivot rows=col[,col..] [cols=col] [value=col] [agg=count|sum|avg|min|max]; :pivot off)",
    ),
    (
        "settings",
        "open the in-app settings editor (:settings / :set) — editor mode, mouse, theme, keybindings",
    ),
    (
        "mode",
        "switch the editor input model on the fly (:mode vim|basic|emacs); persists to settings.toml",
    ),
];

/// Map an alias token back to its primary command key so that `:help o`
/// resolves to the description for "open", not "o".
pub fn resolve_builtin_alias(token: &str) -> &str {
    match token {
        "q" | "exit" => "quit",
        "o" => "open",
        "r" => "refresh",
        "runall" => "run-all",
        "streamall" => "stream-all",
        "dumpschema" => "dump-schema",
        "diag" => "diagram",
        "schemadiff" => "schema-diff",
        "next" | "npage" => "next-page",
        "prev" | "ppage" => "prev-page",
        "pagesize" => "page-size",
        "start" => "begin",
        "abort" => "rollback",
        "sp" => "savepoint",
        "rollbackto" => "rollback-to",
        "rm" => "remove",
        "fmt" => "format",
        "fmtall" => "format-all",
        "plugload" | "plug" => "plug-load",
        "pluglist" | "plugins" => "plug-list",
        "history" => "history",
        "tabnew" => "new",
        "tc" => "tabclose",
        "tn" => "tabnext",
        "tp" | "tabprevious" => "tabprev",
        "h" => "help",
        "noh" => "nohlsearch",
        "rmsnippet" => "rm-snippet",
        "set" => "settings",
        other => other,
    }
}

pub fn parse(input: &str) -> Command {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Command::Empty;
    }
    let mut parts = trimmed.splitn(2, char::is_whitespace);
    let head = parts.next().unwrap_or("");
    let arg = parts.next().unwrap_or("").trim();
    match head {
        "q" | "quit" | "exit" => Command::Quit,
        "open" | "o" => Command::Open(arg.to_owned()),
        "close" => Command::Close,
        "refresh" | "r" => Command::Refresh,
        "run" => Command::Run,
        "run-all" | "runall" => Command::RunAll,
        "stream" => Command::Stream,
        "stream-all" | "streamall" => Command::StreamAll,
        "cancel" => Command::Cancel,
        "clear" => Command::Clear,
        "explain" => Command::Explain,
        "export" => parse_export(arg),
        "dump-schema" | "dumpschema" => parse_dump(arg),
        "diagram" | "diag" => parse_diagram(arg),
        "add" => Command::Add,
        "format" | "fmt" => Command::Format,
        "format-all" | "fmtall" => Command::FormatAll,
        "url" => {
            if arg.is_empty() {
                Command::Unknown("url: dsn required (e.g. :url postgres://user@host/db)".into())
            } else {
                Command::Url(arg.to_owned())
            }
        }
        "test" => {
            if arg.is_empty() {
                Command::Test(None)
            } else {
                Command::Test(Some(arg.to_owned()))
            }
        }
        "edit" => {
            if arg.is_empty() {
                Command::Unknown("edit: connection name required".into())
            } else {
                Command::Edit(arg.to_owned())
            }
        }
        "next" | "next-page" | "npage" => Command::NextPage,
        "prev" | "prev-page" | "ppage" => Command::PrevPage,
        "page-size" | "pagesize" => match arg.parse::<usize>() {
            Ok(n) if n > 0 => Command::PageSize(n),
            _ => Command::Unknown("page-size: expected a positive integer".into()),
        },
        "begin" | "start" => {
            if arg.is_empty() {
                Command::Begin(None)
            } else {
                match IsolationArg::parse(arg) {
                    Some(iso) => Command::Begin(Some(iso)),
                    None => Command::Unknown(format!("begin: unknown isolation '{arg}'")),
                }
            }
        }
        "commit" => Command::Commit,
        "rollback" | "abort" => {
            if arg.is_empty() {
                Command::Rollback
            } else {
                Command::RollbackTo(arg.to_owned())
            }
        }
        "savepoint" | "sp" => {
            if arg.is_empty() {
                Command::Unknown("savepoint: name required".into())
            } else {
                Command::Savepoint(arg.to_owned())
            }
        }
        "release" => {
            if arg.is_empty() {
                Command::Unknown("release: savepoint name required".into())
            } else {
                Command::Release(arg.to_owned())
            }
        }
        "rollback-to" | "rollbackto" => {
            if arg.is_empty() {
                Command::Unknown("rollback-to: savepoint name required".into())
            } else {
                Command::RollbackTo(arg.to_owned())
            }
        }
        "remove" | "rm" => {
            if arg.is_empty() {
                Command::Unknown("remove: connection name required".into())
            } else {
                Command::Remove(arg.to_owned())
            }
        }
        "forget" => {
            if arg.is_empty() {
                Command::Unknown("forget: connection name required".into())
            } else {
                Command::Forget(arg.to_owned())
            }
        }
        "plug-load" | "plugload" | "plug" => {
            if arg.is_empty() {
                Command::Unknown("plug-load: path to .lua file required".into())
            } else {
                Command::PluginLoad(arg.to_owned())
            }
        }
        "plug-list" | "pluglist" | "plugins" => Command::PluginList,
        "history" => {
            let p = arg.trim();
            if p.is_empty() {
                Command::History(None)
            } else {
                // Allow `:history /pattern` (drop the leading slash)
                // for symmetry with vim's reverse search.
                let stripped = p.strip_prefix('/').unwrap_or(p);
                Command::History(Some(stripped.to_owned()))
            }
        }
        "pending" => Command::Pending,
        // `:diff` *without* args still opens the pending
        // preview (legacy alias). With args it's a schema diff.
        "diff" => {
            let trimmed = arg.trim();
            if trimmed.is_empty() {
                Command::Pending
            } else {
                let mut parts = trimmed.split_whitespace();
                match (parts.next(), parts.next()) {
                    (Some(l), Some(r)) => Command::DiffSchema {
                        left: l.to_owned(),
                        right: r.to_owned(),
                    },
                    _ => Command::Unknown(
                        "diff: expected two qualified table names, e.g. :diff public.a public.b"
                            .into(),
                    ),
                }
            }
        }
        "lint" => Command::Lint,
        "pivot" => parse_pivot(arg),
        "tpl" | "template" => {
            let trimmed = arg.trim();
            if trimmed.is_empty() {
                Command::Template(None)
            } else {
                Command::Template(Some(trimmed.to_owned()))
            }
        }
        "diff-schema" => {
            let mut parts = arg.split_whitespace();
            match (parts.next(), parts.next()) {
                (Some(l), Some(r)) => Command::DiffSchema {
                    left: l.to_owned(),
                    right: r.to_owned(),
                },
                _ => Command::Unknown("diff-schema: expected two qualified table names".into()),
            }
        }
        "schema-diff" | "schemadiff" => parse_schema_diff(arg),
        "chart" => parse_chart(arg),
        "submit" | "commit-pending" => Command::Submit,
        "revert" | "discard-pending" => Command::Revert,
        "new" | "tabnew" => Command::NewTab,
        "tabclose" | "tc" => Command::CloseTab,
        "tabnext" | "tn" => Command::NextTab,
        "tabprev" | "tp" | "tabprevious" => Command::PrevTab,
        "help" | "h" => {
            if arg.is_empty() {
                Command::Help(None)
            } else {
                Command::Help(Some(arg.to_owned()))
            }
        }
        "nohlsearch" | "noh" => Command::NoHlSearch,
        "save" => {
            if arg.is_empty() {
                Command::Unknown("save: snippet name required".into())
            } else {
                Command::SaveSnippet {
                    name: arg.to_owned(),
                }
            }
        }
        "load" => {
            if arg.is_empty() {
                Command::Unknown("load: snippet name required".into())
            } else {
                Command::LoadSnippet {
                    name: arg.to_owned(),
                }
            }
        }
        "rm-snippet" | "rmsnippet" => {
            if arg.is_empty() {
                Command::Unknown("rm-snippet: snippet name required".into())
            } else {
                Command::RemoveSnippet {
                    name: arg.to_owned(),
                }
            }
        }
        "snippets" => Command::ListSnippets,
        "goto" | "g" => Command::Goto,
        "settings" | "set" => Command::Settings,
        "mode" => Command::Mode(arg.to_owned()),
        "filter" => {
            // `:filter` (no arg)        → open inline prompt
            // `:filter clear`           → drop the active filter
            // `:filter <expr>`          → set the filter expression
            if arg.trim().is_empty() {
                Command::Filter(None)
            } else if arg.trim().eq_ignore_ascii_case("clear") {
                Command::Filter(Some(String::new()))
            } else {
                Command::Filter(Some(arg.to_owned()))
            }
        }
        "sort" => {
            let arg = arg.trim();
            if arg.is_empty() || arg.eq_ignore_ascii_case("clear") {
                Command::Sort(SortArg::Clear)
            } else {
                match arg.parse::<usize>() {
                    Ok(n) if n >= 1 => Command::Sort(SortArg::Column(n)),
                    _ => {
                        Command::Unknown("sort: expected a 1-based column number or 'clear'".into())
                    }
                }
            }
        }
        _ => {
            // Try substitute: s/pat/rep/[gc] or %s/pat/rep/[gc]
            if let Some(cmd) = try_parse_substitute(trimmed) {
                cmd
            } else {
                Command::Unknown(trimmed.to_owned())
            }
        }
    }
}

fn parse_dump(arg: &str) -> Command {
    let trimmed = arg.trim();
    let target = match trimmed {
        "" => DumpTarget::Current,
        "*" | "all" => DumpTarget::All,
        name => DumpTarget::Named(name.to_owned()),
    };
    Command::DumpSchema { target }
}

fn parse_export(arg: &str) -> Command {
    // Split into `format` + remainder so paths containing spaces stay
    // intact. The split_whitespace + take(2) shape that used to live
    // here rejected `:export csv /tmp/my data.csv` with a confusing
    // "too many arguments" error.
    let trimmed = arg.trim_start();
    let (format, rest) = match trimmed.split_once(char::is_whitespace) {
        Some((f, r)) => (f, r.trim_start()),
        None => (trimmed, ""),
    };
    if format.is_empty() {
        return Command::Unknown(
            "export: format required (csv|json|tsv|table|insert|parquet|markdown)".into(),
        );
    }
    // the path may be followed by `--compression <codec>` or
    // `--no-truncate`. Strip the trailing flags first so a path with
    // spaces survives; what remains is the path proper. The flags are
    // intentionally trailing-only so `:export markdown out.md` keeps
    // the historical positional shape.
    let (path, options) = match split_export_flags(rest) {
        Ok(parsed) => parsed,
        Err(msg) => return Command::Unknown(msg),
    };
    let path = path.trim_end();
    if path.is_empty() {
        return Command::Unknown("export: path required".into());
    }
    Command::Export {
        format: format.to_owned(),
        path: path.to_owned(),
        options,
    }
}

/// Trailing-flag parser for `:export`. Walks tokens from the right
/// peeling off `--no-truncate` and `--compression <codec>` until a
/// non-flag token is hit; everything before that point is the path.
///
/// The trailing-only contract is what lets the path keep interior
/// spaces (`:export markdown /tmp/my report.md --no-truncate`): once
/// we stop seeing flags, the entire prefix — spaces and all — is the
/// path.
fn split_export_flags(rest: &str) -> Result<(&str, ExportArgs), String> {
    let mut args = ExportArgs::default();
    let mut cursor = rest.trim_end();
    loop {
        // Peel the last whitespace-separated token off `cursor`.
        let (head, last) = match cursor.rfind(char::is_whitespace) {
            Some(boundary) => {
                let (prefix, suffix) = cursor.split_at(boundary);
                (prefix.trim_end(), suffix.trim_start())
            }
            None => ("", cursor),
        };
        match last {
            "--no-truncate" => {
                args.no_truncate = true;
                cursor = head;
            }
            "--compression" => {
                // Bare `--compression` with no value is a user error.
                return Err("export: --compression requires a codec (snappy|zstd|none)".into());
            }
            // Any other token might be the path or the value half of
            // `--compression <codec>`. Peek one further left.
            value if !value.is_empty() => {
                let (head2, prev) = match head.rfind(char::is_whitespace) {
                    Some(b) => {
                        let (p, s) = head.split_at(b);
                        (p.trim_end(), s.trim_start())
                    }
                    None => ("", head),
                };
                if prev == "--compression" {
                    let Some(codec) = crate::export::ParquetCompression::from_token(value) else {
                        return Err(format!(
                            "export: unknown compression `{value}` (snappy|zstd|none)"
                        ));
                    };
                    args.compression = Some(codec);
                    cursor = head2;
                    continue;
                }
                // Not a flag pair — stop; what we have is the path.
                break;
            }
            _ => break,
        }
    }
    Ok((cursor, args))
}

/// Parse the argument to `:diagram`. Grammar:
///
/// ```text
/// export <format> [path] [--table NAME] [--schema NAME]
/// impact <table>
/// focus  <table>                # explicit Focused modal
/// -- <table>                    # bare-table escape (when table is `export` / `impact` / `focus`)
/// <table>                       # implicit Focused modal (muscle-memory form)
/// ```
///
/// `format` is one of `mermaid|mmd|mer|dot|gv|graphviz`. `path` is the
/// first positional argument that is not a flag; if absent, the rendered
/// diagram goes to the system clipboard. `--table` / `-t` restricts the
/// diagram to a single table and its 1-hop FK neighbours.
///
/// The bare `<table>` form is intentionally positional so muscle-memory
/// like `:diagram users` works without remembering a subcommand. If
/// the table is literally named `export`, `impact`, or `focus` (rare
/// but legal), use `:diagram -- export` to force the focused-modal path
/// or `:diagram focus export` for the same effect spelled out.
fn parse_diagram(arg: &str) -> Command {
    let trimmed = arg.trim();
    if trimmed.is_empty() {
        return Command::Unknown(
            "diagram: subcommand or table name required (try `:diagram users`)".into(),
        );
    }
    let (sub, rest) = match trimmed.split_once(char::is_whitespace) {
        Some((s, r)) => (s, r.trim()),
        None => (trimmed, ""),
    };
    match sub {
        "export" => parse_diagram_export(rest),
        "impact" => parse_diagram_table_subcommand("impact", rest, Command::DiagramImpact),
        "focus" => parse_diagram_table_subcommand("focus", rest, Command::DiagramFocus),
        // `:diagram -- <table>` escapes a literal table named
        // `export`, `impact` or `focus`. The escape must be followed
        // by exactly one argument; otherwise the user almost certainly
        // meant something else.
        "--" => {
            if rest.is_empty() {
                return Command::Unknown("diagram --: table name required after the escape".into());
            }
            if rest.split_whitespace().count() > 1 {
                return Command::Unknown(format!(
                    "diagram --: unexpected extra arguments after '{}'",
                    rest.split_whitespace().next().unwrap_or("")
                ));
            }
            Command::DiagramFocus(rest.to_owned())
        }
        // Bare positional: sub *is* the table name.
        table => {
            if !rest.is_empty() {
                return Command::Unknown(format!(
                    "diagram: unexpected argument '{rest}' after table name"
                ));
            }
            Command::DiagramFocus(table.to_owned())
        }
    }
}

/// Shared body for `:diagram impact <table>` and `:diagram focus <table>`.
/// Both subcommands take exactly one positional argument; reject every
/// other shape with a friendly error.
fn parse_diagram_table_subcommand(
    sub: &str,
    rest: &str,
    builder: fn(String) -> Command,
) -> Command {
    if rest.is_empty() {
        return Command::Unknown(format!("diagram {sub}: table name required"));
    }
    if rest.split_whitespace().count() > 1 {
        return Command::Unknown(format!(
            "diagram {sub}: unexpected extra arguments after '{}'",
            rest.split_whitespace().next().unwrap_or("")
        ));
    }
    builder(rest.to_owned())
}

/// Parse `:schema-diff source target [--dialect d] [--schema s]
/// [--table t] [--schema-map src=tgt]...`.
///
/// Two positional args (source + target connection names) are
/// required. Repeating `--schema-map` builds the rename map. The
/// `--out` flag is intentionally **omitted** from the TUI parser:
/// the in-editor render is the whole point of the TUI command. Use
/// the `narwhal schema-diff` headless subcommand when you want a
/// file.
fn parse_schema_diff(arg: &str) -> Command {
    let mut tokens = arg.split_whitespace();
    let mut positional: Vec<String> = Vec::new();
    let mut dialect: Option<String> = None;
    let mut schema: Option<String> = None;
    let mut table: Option<String> = None;
    let mut schema_map: Vec<(String, String)> = Vec::new();

    while let Some(tok) = tokens.next() {
        match tok {
            "--dialect" => {
                let Some(value) = tokens.next() else {
                    return Command::Unknown("schema-diff: --dialect requires a value".into());
                };
                dialect = Some(value.to_owned());
            }
            "--schema" => {
                let Some(value) = tokens.next() else {
                    return Command::Unknown("schema-diff: --schema requires a value".into());
                };
                schema = Some(value.to_owned());
            }
            "--table" => {
                let Some(value) = tokens.next() else {
                    return Command::Unknown("schema-diff: --table requires a value".into());
                };
                table = Some(value.to_owned());
            }
            "--schema-map" => {
                let Some(value) = tokens.next() else {
                    return Command::Unknown(
                        "schema-diff: --schema-map requires a source=target value".into(),
                    );
                };
                let Some((src, tgt)) = value.split_once('=') else {
                    return Command::Unknown(format!(
                        "schema-diff: --schema-map expects `source=target`, got `{value}`"
                    ));
                };
                if src.is_empty() || tgt.is_empty() {
                    return Command::Unknown(format!(
                        "schema-diff: --schema-map: empty side in `{value}`"
                    ));
                }
                schema_map.push((src.to_owned(), tgt.to_owned()));
            }
            other if other.starts_with("--") => {
                return Command::Unknown(format!("schema-diff: unknown flag '{other}'"));
            }
            other => positional.push(other.to_owned()),
        }
    }

    if positional.len() != 2 {
        return Command::Unknown(
            "schema-diff: expected two connection names \
             (`:schema-diff source target [--dialect ..] [--schema ..] [--table ..] \
             [--schema-map src=tgt]`)"
                .into(),
        );
    }
    // length checked above; destructure to keep the invariant honest.
    let [source, target]: [String; 2] = match positional.try_into() {
        Ok(arr) => arr,
        Err(_) => unreachable!("positional.len() == 2 guarded above"),
    };

    Command::SchemaDiff {
        source,
        target,
        dialect,
        schema,
        table,
        schema_map,
    }
}

/// Parse the argument to `:chart`. Grammar:
///
/// ```text
/// bar|line|sparkline [--x col] [--y col] [--col col] [--title T]
/// off|none
/// ```
///
/// `--col` is an alias for `--y` so the sparkline form
/// (`:chart sparkline --col revenue`) reads naturally. `--x` on a
/// sparkline is silently accepted but stored — the renderer ignores
/// it.
fn parse_chart(arg: &str) -> Command {
    let trimmed = arg.trim();
    if trimmed.is_empty() {
        return Command::Unknown("chart: subcommand required (bar|line|sparkline|off)".into());
    }
    let mut tokens = trimmed.split_whitespace();
    let Some(head) = tokens.next() else {
        return Command::Unknown("chart: subcommand required (bar|line|sparkline|off)".into());
    };
    let lower = head.to_ascii_lowercase();
    if matches!(lower.as_str(), "off" | "none" | "hide") {
        if tokens.next().is_some() {
            return Command::Unknown("chart off: no extra arguments expected".into());
        }
        return Command::Chart(ChartArg::Off);
    }
    let Some(kind) = ChartKindArg::from_token(&lower) else {
        return Command::Unknown(format!(
            "chart: unknown subcommand '{head}' (expected bar|line|sparkline|off)"
        ));
    };

    let mut x_col: Option<String> = None;
    let mut y_col: Option<String> = None;
    let mut title: Option<String> = None;

    while let Some(tok) = tokens.next() {
        match tok {
            "--x" | "-x" => {
                let Some(value) = tokens.next() else {
                    return Command::Unknown("chart: --x requires a column name".into());
                };
                x_col = Some(value.to_owned());
            }
            "--y" | "-y" | "--col" | "-c" => {
                let Some(value) = tokens.next() else {
                    return Command::Unknown("chart: --y / --col requires a column name".into());
                };
                y_col = Some(value.to_owned());
            }
            "--title" | "-t" => {
                let Some(value) = tokens.next() else {
                    return Command::Unknown("chart: --title requires a value".into());
                };
                title = Some(value.to_owned());
            }
            other if other.starts_with("--") => {
                return Command::Unknown(format!("chart: unknown flag '{other}'"));
            }
            other => {
                return Command::Unknown(format!(
                    "chart: unexpected argument '{other}' (use --x / --y / --title)"
                ));
            }
        }
    }

    Command::Chart(ChartArg::On {
        kind,
        title,
        x_col,
        y_col,
    })
}

fn parse_diagram_export(rest: &str) -> Command {
    let mut tokens = rest.split_whitespace();
    let Some(format_tok) = tokens.next() else {
        return Command::Unknown("diagram: format required (mermaid|dot)".into());
    };
    let Some(format) = DiagramFormat::from_token(format_tok) else {
        return Command::Unknown(format!(
            "diagram: unknown format '{format_tok}' (mermaid|dot)"
        ));
    };

    let mut path: Option<String> = None;
    let mut table: Option<String> = None;
    let mut schema: Option<String> = None;
    while let Some(tok) = tokens.next() {
        match tok {
            "--table" | "-t" => {
                let Some(value) = tokens.next() else {
                    return Command::Unknown("diagram: --table requires a table name".into());
                };
                table = Some(value.to_owned());
            }
            "--schema" | "-s" => {
                let Some(value) = tokens.next() else {
                    return Command::Unknown("diagram: --schema requires a schema name".into());
                };
                schema = Some(value.to_owned());
            }
            other if other.starts_with("--") => {
                return Command::Unknown(format!("diagram: unknown flag '{other}'"));
            }
            other => {
                if path.is_some() {
                    return Command::Unknown(format!("diagram: unexpected argument '{other}'"));
                }
                path = Some(other.to_owned());
            }
        }
    }

    Command::DiagramExport {
        format,
        path,
        table,
        schema,
    }
}

/// Try to parse `:s/pat/rep/[gc]` or `:%s/pat/rep/[gc]`.
/// Returns `None` if the input doesn't match the substitute pattern.
/// Parse the argument to `:pivot`. Grammar:
///
/// ```text
/// rows=col1[,col2..] [cols=col] [value=col] [agg=count|sum|avg|min|max]
/// off|none
/// ```
///
/// Tokens are `key=value` pairs; order-independent. `rows=` accepts a
/// comma-separated list and may be omitted only when `cols=` is
/// present. Missing `agg` defaults to `count`.
fn parse_pivot(arg: &str) -> Command {
    let trimmed = arg.trim();
    if trimmed.is_empty() {
        return Command::Unknown(
            "pivot: subcommand required (rows=col[,col..] [cols=col] [value=col] [agg=fn]; or off)"
                .into(),
        );
    }
    let lower_head = trimmed
        .split_whitespace()
        .next()
        .unwrap_or("")
        .to_ascii_lowercase();
    if matches!(lower_head.as_str(), "off" | "none" | "hide") {
        if trimmed.split_whitespace().count() > 1 {
            return Command::Unknown("pivot off: no extra arguments expected".into());
        }
        return Command::Pivot(PivotArg::Off);
    }

    let mut rows: Vec<String> = Vec::new();
    let mut cols: Option<String> = None;
    let mut value: Option<String> = None;
    let mut agg: PivotAggArg = PivotAggArg::Count;
    let mut saw_agg = false;

    for token in trimmed.split_whitespace() {
        let Some((key, val)) = token.split_once('=') else {
            return Command::Unknown(format!("pivot: expected key=value pair, got '{token}'"));
        };
        if val.is_empty() {
            return Command::Unknown(format!("pivot: '{key}' needs a value"));
        }
        match key.to_ascii_lowercase().as_str() {
            "rows" | "row" | "r" => {
                rows = val
                    .split(',')
                    .map(|s| s.trim().to_owned())
                    .filter(|s| !s.is_empty())
                    .collect();
                if rows.is_empty() {
                    return Command::Unknown("pivot: rows= needs at least one column".into());
                }
            }
            "cols" | "col" | "c" => cols = Some(val.to_owned()),
            "value" | "val" | "v" => value = Some(val.to_owned()),
            "agg" | "a" => {
                let Some(parsed) = PivotAggArg::from_token(val) else {
                    return Command::Unknown(format!(
                        "pivot: unknown aggregator '{val}' (expected count|sum|avg|min|max)"
                    ));
                };
                agg = parsed;
                saw_agg = true;
            }
            other => {
                return Command::Unknown(format!("pivot: unknown key '{other}'"));
            }
        }
    }

    if rows.is_empty() && cols.is_none() {
        return Command::Unknown("pivot: at least one of rows= or cols= is required".into());
    }
    // sum / avg / min / max all need a value column. The dispatch
    // layer will surface a richer error if the column is non-numeric.
    if matches!(
        agg,
        PivotAggArg::Sum | PivotAggArg::Avg | PivotAggArg::Min | PivotAggArg::Max
    ) && value.is_none()
    {
        return Command::Unknown(format!(
            "pivot: agg={} requires value=<col>",
            match agg {
                PivotAggArg::Sum => "sum",
                PivotAggArg::Avg => "avg",
                PivotAggArg::Min => "min",
                PivotAggArg::Max => "max",
                PivotAggArg::Count => unreachable!(),
            }
        ));
    }
    let _ = saw_agg; // suppress unused-var lint without `_` rename

    Command::Pivot(PivotArg::On {
        rows,
        cols,
        value,
        agg,
    })
}

fn try_parse_substitute(input: &str) -> Option<Command> {
    let (range, rest) = if let Some(r) = input.strip_prefix("%s/") {
        (SubstituteRange::WholeBuffer, r)
    } else if let Some(r) = input.strip_prefix("s/") {
        (SubstituteRange::CurrentLine, r)
    } else {
        return None;
    };

    // Split on `/` — we need at least pattern/replacement/
    let mut slash_iter = rest.splitn(3, '/');
    let pattern = slash_iter.next().unwrap_or("").to_owned();
    let replacement = slash_iter.next().unwrap_or("").to_owned();
    let flags = slash_iter.next().unwrap_or("");

    if pattern.is_empty() {
        return Some(Command::Unknown("substitute: empty pattern".into()));
    }

    let global = flags.contains('g');
    let confirm = flags.contains('c');

    Some(Command::Substitute {
        range,
        pattern,
        replacement,
        global,
        confirm,
    })
}

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

    #[test]
    fn aliases() {
        assert_eq!(parse(":q"), Command::Unknown(":q".into()));
        assert_eq!(parse("q"), Command::Quit);
        assert_eq!(parse("quit"), Command::Quit);
        assert_eq!(parse("exit"), Command::Quit);
        assert_eq!(parse("o prod"), Command::Open("prod".into()));
        assert_eq!(parse("open  prod-db  "), Command::Open("prod-db".into()));
        assert_eq!(parse("run-all"), Command::RunAll);
        assert_eq!(parse("stream"), Command::Stream);
        assert_eq!(parse("stream-all"), Command::StreamAll);
        assert_eq!(
            parse("export csv /tmp/out.csv"),
            Command::Export {
                format: "csv".into(),
                path: "/tmp/out.csv".into(),
                options: ExportArgs::default(),
            }
        );
        assert_eq!(
            parse("dump-schema"),
            Command::DumpSchema {
                target: DumpTarget::Current
            }
        );
        assert_eq!(
            parse("dump-schema all"),
            Command::DumpSchema {
                target: DumpTarget::All
            }
        );
        assert_eq!(
            parse("dump-schema orders"),
            Command::DumpSchema {
                target: DumpTarget::Named("orders".into())
            }
        );
        assert_eq!(
            parse("diagram export mermaid"),
            Command::DiagramExport {
                format: DiagramFormat::Mermaid,
                path: None,
                table: None,
                schema: None,
            }
        );
        assert_eq!(
            parse("diag export dot ./schema.dot"),
            Command::DiagramExport {
                format: DiagramFormat::Dot,
                path: Some("./schema.dot".into()),
                table: None,
                schema: None,
            }
        );
        assert_eq!(
            parse("diagram export mmd --table users"),
            Command::DiagramExport {
                format: DiagramFormat::Mermaid,
                path: None,
                table: Some("users".into()),
                schema: None,
            }
        );
        assert_eq!(
            parse("diagram export mermaid /tmp/x.mmd -t orders -s public"),
            Command::DiagramExport {
                format: DiagramFormat::Mermaid,
                path: Some("/tmp/x.mmd".into()),
                table: Some("orders".into()),
                schema: Some("public".into()),
            }
        );
        match parse("diagram export") {
            Command::Unknown(msg) => assert!(msg.contains("format")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        match parse("diagram export svg") {
            Command::Unknown(msg) => assert!(msg.contains("unknown format")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        // Bare positional `:diagram <table>` opens Focused modal.
        assert_eq!(
            parse("diagram users"),
            Command::DiagramFocus("users".into())
        );
        assert_eq!(
            parse("diagram public.orders"),
            Command::DiagramFocus("public.orders".into())
        );
        assert_eq!(parse("diag orders"), Command::DiagramFocus("orders".into()));
        // `:diagram impact <table>` opens Impact modal.
        assert_eq!(
            parse("diagram impact users"),
            Command::DiagramImpact("users".into())
        );
        match parse("diagram impact") {
            Command::Unknown(msg) => assert!(msg.contains("table name required")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        match parse("diagram impact users extra") {
            Command::Unknown(msg) => assert!(msg.contains("unexpected extra")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        match parse("diagram users extra") {
            Command::Unknown(msg) => assert!(msg.contains("unexpected argument")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        // `:diagram focus <table>` spells out the implicit form so
        // tables literally named `export` / `impact` / `focus` are
        // reachable.
        assert_eq!(
            parse("diagram focus export"),
            Command::DiagramFocus("export".into())
        );
        assert_eq!(
            parse("diagram focus public.impact"),
            Command::DiagramFocus("public.impact".into())
        );
        match parse("diagram focus") {
            Command::Unknown(msg) => assert!(msg.contains("table name required")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        // `:diagram -- <table>` escape for the muscle-memory form when
        // the table literally collides with a subcommand name.
        assert_eq!(
            parse("diagram -- export"),
            Command::DiagramFocus("export".into())
        );
        assert_eq!(
            parse("diagram -- impact"),
            Command::DiagramFocus("impact".into())
        );
        match parse("diagram --") {
            Command::Unknown(msg) => assert!(msg.contains("table name required")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        match parse("diagram -- a b") {
            Command::Unknown(msg) => assert!(msg.contains("unexpected extra")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        match parse("diagram export mermaid --table") {
            Command::Unknown(msg) => assert!(msg.contains("--table requires")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        assert_eq!(parse("new"), Command::NewTab);
        assert_eq!(parse("tabnew"), Command::NewTab);
        assert_eq!(parse("tabclose"), Command::CloseTab);
        assert_eq!(parse("tabnext"), Command::NextTab);
        assert_eq!(parse("tabprev"), Command::PrevTab);
        assert_eq!(parse("next"), Command::NextPage);
        assert_eq!(parse("prev-page"), Command::PrevPage);
        assert_eq!(parse("page-size 50"), Command::PageSize(50));
        match parse("page-size 0") {
            Command::Unknown(msg) => assert!(msg.contains("positive")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        assert_eq!(parse("begin"), Command::Begin(None));
        assert_eq!(
            parse("begin serializable"),
            Command::Begin(Some(IsolationArg::Serializable))
        );
        assert_eq!(
            parse("begin read-committed"),
            Command::Begin(Some(IsolationArg::ReadCommitted))
        );
        assert_eq!(parse("commit"), Command::Commit);
        assert_eq!(parse("rollback"), Command::Rollback);
        assert_eq!(parse("rollback sp1"), Command::RollbackTo("sp1".into()));
        assert_eq!(parse("savepoint sp1"), Command::Savepoint("sp1".into()));
        assert_eq!(parse("sp sp2"), Command::Savepoint("sp2".into()));
        assert_eq!(parse("release sp1"), Command::Release("sp1".into()));
        assert_eq!(parse("rollback-to sp1"), Command::RollbackTo("sp1".into()));
        match parse("begin bogus") {
            Command::Unknown(msg) => assert!(msg.contains("isolation")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        assert_eq!(parse("remove dev"), Command::Remove("dev".into()));
        assert_eq!(parse("rm  prod "), Command::Remove("prod".into()));
        assert_eq!(parse("forget dev"), Command::Forget("dev".into()));
        match parse("remove") {
            Command::Unknown(msg) => assert!(msg.contains("connection name")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        match parse("export") {
            Command::Unknown(msg) => assert!(msg.contains("format required")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        // Round 2 bugfix: paths with spaces used to be rejected with
        // a confusing "too many arguments" error.
        assert_eq!(
            parse("export csv /tmp/my data.csv"),
            Command::Export {
                format: "csv".into(),
                path: "/tmp/my data.csv".into(),
                options: ExportArgs::default(),
            }
        );
        // Trailing whitespace gets trimmed but interior spaces survive.
        assert_eq!(
            parse("export json   /tmp/two words.json   "),
            Command::Export {
                format: "json".into(),
                path: "/tmp/two words.json".into(),
                options: ExportArgs::default(),
            }
        );

        // parquet + markdown with their flags.
        use crate::export::ParquetCompression;
        assert_eq!(
            parse("export parquet out.parquet --compression zstd"),
            Command::Export {
                format: "parquet".into(),
                path: "out.parquet".into(),
                options: ExportArgs {
                    compression: Some(ParquetCompression::Zstd),
                    no_truncate: false,
                },
            }
        );
        assert_eq!(
            parse("export markdown out.md --no-truncate"),
            Command::Export {
                format: "markdown".into(),
                path: "out.md".into(),
                options: ExportArgs {
                    compression: None,
                    no_truncate: true,
                },
            }
        );
        // `md` alias + path with a space still works under flags.
        assert_eq!(
            parse("export md /tmp/my report.md --no-truncate"),
            Command::Export {
                format: "md".into(),
                path: "/tmp/my report.md".into(),
                options: ExportArgs {
                    compression: None,
                    no_truncate: true,
                },
            }
        );
        // Both flags at once.
        assert_eq!(
            parse("export parquet out.parquet --compression none"),
            Command::Export {
                format: "parquet".into(),
                path: "out.parquet".into(),
                options: ExportArgs {
                    compression: Some(ParquetCompression::None),
                    no_truncate: false,
                },
            }
        );
        // Bad codec surfaces a friendly error rather than crashing.
        match parse("export parquet out.parquet --compression brotli") {
            Command::Unknown(msg) => assert!(msg.contains("brotli")),
            other => panic!("expected Unknown, got {other:?}"),
        }
        // Bare `--compression` without a codec is rejected.
        match parse("export parquet out.parquet --compression") {
            Command::Unknown(msg) => assert!(msg.contains("requires a codec")),
            other => panic!("expected Unknown, got {other:?}"),
        }
    }

    #[test]
    fn empty_and_unknown() {
        assert_eq!(parse(""), Command::Empty);
        assert_eq!(parse("   "), Command::Empty);
        assert_eq!(parse("zz"), Command::Unknown("zz".into()));
    }

    // parser coverage.
    #[test]
    fn schema_diff_minimal() {
        let cmd = parse("schema-diff prod staging");
        assert_eq!(
            cmd,
            Command::SchemaDiff {
                source: "prod".into(),
                target: "staging".into(),
                dialect: None,
                schema: None,
                table: None,
                schema_map: Vec::new(),
            }
        );
    }

    #[test]
    fn schema_diff_with_flags() {
        let cmd = parse(
            "schema-diff prod staging --dialect postgres --schema public \
             --table users --schema-map prod_app=staging_app \
             --schema-map prod_log=staging_log",
        );
        let Command::SchemaDiff {
            source,
            target,
            dialect,
            schema,
            table,
            schema_map,
        } = cmd
        else {
            panic!("expected SchemaDiff, got {cmd:?}");
        };
        assert_eq!(source, "prod");
        assert_eq!(target, "staging");
        assert_eq!(dialect.as_deref(), Some("postgres"));
        assert_eq!(schema.as_deref(), Some("public"));
        assert_eq!(table.as_deref(), Some("users"));
        assert_eq!(
            schema_map,
            vec![
                ("prod_app".to_owned(), "staging_app".to_owned()),
                ("prod_log".to_owned(), "staging_log".to_owned()),
            ]
        );
    }

    #[test]
    fn schema_diff_alias_resolves() {
        // `schemadiff` (no hyphen) routes through the same parser.
        let cmd = parse("schemadiff src tgt");
        assert!(matches!(cmd, Command::SchemaDiff { .. }));
    }

    #[test]
    fn schema_diff_missing_target_is_unknown() {
        let cmd = parse("schema-diff onlyone");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("expected two connection names"), "got: {msg}");
    }

    #[test]
    fn schema_diff_malformed_map_is_unknown() {
        let cmd = parse("schema-diff a b --schema-map noequals");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("--schema-map expects"), "got: {msg}");
    }

    #[test]
    fn schema_diff_unknown_flag_is_rejected() {
        let cmd = parse("schema-diff a b --bogus");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("unknown flag"), "got: {msg}");
    }

    #[test]
    fn chart_bar_defaults() {
        assert_eq!(
            parse("chart bar"),
            Command::Chart(ChartArg::On {
                kind: ChartKindArg::Bar,
                title: None,
                x_col: None,
                y_col: None,
            })
        );
    }

    #[test]
    fn chart_off_dismisses() {
        assert_eq!(parse("chart off"), Command::Chart(ChartArg::Off));
        assert_eq!(parse("chart none"), Command::Chart(ChartArg::Off));
        assert_eq!(parse("chart hide"), Command::Chart(ChartArg::Off));
    }

    #[test]
    fn chart_off_rejects_extra_args() {
        let cmd = parse("chart off bogus");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("no extra arguments"), "got: {msg}");
    }

    #[test]
    fn chart_line_with_x_and_y_overrides() {
        assert_eq!(
            parse("chart line --x ts --y revenue"),
            Command::Chart(ChartArg::On {
                kind: ChartKindArg::Line,
                title: None,
                x_col: Some("ts".into()),
                y_col: Some("revenue".into()),
            })
        );
    }

    #[test]
    fn chart_sparkline_col_alias() {
        assert_eq!(
            parse("chart sparkline --col revenue"),
            Command::Chart(ChartArg::On {
                kind: ChartKindArg::Sparkline,
                title: None,
                x_col: None,
                y_col: Some("revenue".into()),
            })
        );
        // Short alias `spark` is also accepted.
        assert_eq!(
            parse("chart spark -c revenue"),
            Command::Chart(ChartArg::On {
                kind: ChartKindArg::Sparkline,
                title: None,
                x_col: None,
                y_col: Some("revenue".into()),
            })
        );
    }

    #[test]
    fn chart_title_flag() {
        assert_eq!(
            parse("chart bar --title sales"),
            Command::Chart(ChartArg::On {
                kind: ChartKindArg::Bar,
                title: Some("sales".into()),
                x_col: None,
                y_col: None,
            })
        );
    }

    #[test]
    fn chart_requires_subcommand() {
        let cmd = parse("chart");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("subcommand required"), "got: {msg}");
    }

    #[test]
    fn chart_unknown_kind_is_rejected() {
        let cmd = parse("chart pie");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("unknown subcommand"), "got: {msg}");
    }

    #[test]
    fn chart_unknown_flag_is_rejected() {
        let cmd = parse("chart bar --bogus value");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("unknown flag"), "got: {msg}");
    }

    #[test]
    fn chart_flag_without_value_errors() {
        let cmd = parse("chart bar --x");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("--x requires"), "got: {msg}");
    }

    #[test]
    fn pivot_minimal_rows_only() {
        assert_eq!(
            parse("pivot rows=country"),
            Command::Pivot(PivotArg::On {
                rows: vec!["country".into()],
                cols: None,
                value: None,
                agg: PivotAggArg::Count,
            })
        );
    }

    #[test]
    fn pivot_full_spec() {
        assert_eq!(
            parse("pivot rows=country,year cols=segment value=revenue agg=sum"),
            Command::Pivot(PivotArg::On {
                rows: vec!["country".into(), "year".into()],
                cols: Some("segment".into()),
                value: Some("revenue".into()),
                agg: PivotAggArg::Sum,
            })
        );
    }

    #[test]
    fn pivot_off_aliases() {
        assert_eq!(parse("pivot off"), Command::Pivot(PivotArg::Off));
        assert_eq!(parse("pivot none"), Command::Pivot(PivotArg::Off));
        assert_eq!(parse("pivot hide"), Command::Pivot(PivotArg::Off));
    }

    #[test]
    fn pivot_off_rejects_extra_args() {
        let cmd = parse("pivot off bogus");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("no extra arguments"), "got: {msg}");
    }

    #[test]
    fn pivot_requires_dim() {
        let cmd = parse("pivot agg=sum value=revenue");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("rows= or cols="), "got: {msg}");
    }

    #[test]
    fn pivot_sum_requires_value() {
        let cmd = parse("pivot rows=country agg=sum");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("requires value="), "got: {msg}");
    }

    #[test]
    fn pivot_rejects_unknown_agg() {
        let cmd = parse("pivot rows=k agg=median");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("unknown aggregator"), "got: {msg}");
    }

    #[test]
    fn pivot_rejects_unknown_key() {
        let cmd = parse("pivot rows=k foo=bar");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("unknown key"), "got: {msg}");
    }

    #[test]
    fn pivot_rejects_malformed_token() {
        let cmd = parse("pivot rows");
        let Command::Unknown(msg) = cmd else {
            panic!("expected Unknown, got {cmd:?}");
        };
        assert!(msg.contains("key=value"), "got: {msg}");
    }

    #[test]
    fn pivot_aggregator_aliases() {
        for (token, expected) in [
            ("sum", PivotAggArg::Sum),
            ("total", PivotAggArg::Sum),
            ("mean", PivotAggArg::Avg),
            ("n", PivotAggArg::Count),
        ] {
            assert_eq!(PivotAggArg::from_token(token), Some(expected));
        }
    }
    /// `:help <cmd>` walks `BUILTIN_COMMAND_DESCRIPTIONS` after
    /// resolving aliases through `resolve_builtin_alias`. The lookup
    /// only stays useful as long as every parser-accepted built-in
    /// (and every alias it accepts) resolves to a primary key that
    /// has a description entry. Without this test, adding a new
    /// command to `BUILTIN_COMMAND_NAMES` + parser without touching
    /// `BUILTIN_COMMAND_DESCRIPTIONS` silently makes `:help <newcmd>`
    /// report "unknown command".
    #[test]
    fn every_builtin_command_name_has_a_description() {
        for &name in BUILTIN_COMMAND_NAMES {
            let primary = resolve_builtin_alias(name);
            assert!(
                BUILTIN_COMMAND_DESCRIPTIONS
                    .iter()
                    .any(|(key, _)| *key == primary),
                "BUILTIN_COMMAND_NAMES contains '{name}' (resolves to '{primary}') \
                 but BUILTIN_COMMAND_DESCRIPTIONS has no entry for it"
            );
        }
    }
}