cargo-port 0.0.3

A TUI for inspecting and managing Rust projects
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
use std::collections::HashMap;
use std::fmt;
use std::fmt::Write as _;
use std::str::FromStr;

use crossterm::event::KeyCode;
use crossterm::event::KeyModifiers;

use crate::config::NavigationKeys;
use crate::project::AbsolutePath;

// ── Key representation ───────────────────────────────────────────────

/// A bindable key: a `KeyCode` plus modifier flags from crossterm.
///
/// `=` and `+` are normalised to a single canonical form (`+`) so they
/// are treated as the same physical key.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct KeyBind {
    pub code:      KeyCode,
    pub modifiers: KeyModifiers,
}

impl KeyBind {
    pub(crate) fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
        // BackTab implies Shift — normalise to Tab + SHIFT.
        // Uppercase Char implies Shift — strip SHIFT since it's
        // encoded in the character itself (`Char('R')` already means
        // Shift+r).  This ensures the binding `"R"` matches the
        // crossterm event `Char('R') + SHIFT`.
        // Normalise Shift + lowercase letter → uppercase letter with
        // SHIFT stripped, so `Shift+r` and `R` produce the same KeyBind.
        let (code, modifiers) = match code {
            KeyCode::BackTab => (code, modifiers | KeyModifiers::SHIFT),
            KeyCode::Char(c)
                if c.is_ascii_lowercase() && modifiers.contains(KeyModifiers::SHIFT) =>
            {
                (
                    KeyCode::Char(c.to_ascii_uppercase()),
                    modifiers - KeyModifiers::SHIFT,
                )
            },
            KeyCode::Char(c) if c.is_ascii_uppercase() => (code, modifiers - KeyModifiers::SHIFT),
            _ => (code, modifiers),
        };
        Self {
            code: normalize_code(code),
            modifiers,
        }
    }

    pub(crate) fn plain(code: KeyCode) -> Self { Self::new(code, KeyModifiers::NONE) }

    /// Human-readable glyph string for display in status bar / keymap UI.
    pub(crate) fn display(&self) -> String {
        let mut parts = String::new();
        if self.modifiers.contains(KeyModifiers::CONTROL) {
            parts.push('');
        }
        if self.modifiers.contains(KeyModifiers::ALT) {
            parts.push('');
        }
        if self.modifiers.contains(KeyModifiers::SHIFT) {
            parts.push('');
        }
        parts.push_str(&code_label(self.code));
        parts
    }

    /// TOML-serialisable string (e.g. `"Ctrl+r"`, `"Shift+Tab"`, `"q"`).
    pub(crate) fn to_toml_string(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        if self.modifiers.contains(KeyModifiers::CONTROL) {
            parts.push("Ctrl".to_string());
        }
        if self.modifiers.contains(KeyModifiers::ALT) {
            parts.push("Alt".to_string());
        }
        if self.modifiers.contains(KeyModifiers::SHIFT) {
            parts.push("Shift".to_string());
        }
        parts.push(code_label(self.code));
        parts.join("+")
    }
}

impl fmt::Display for KeyBind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.display()) }
}

impl FromStr for KeyBind {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> { parse_keybind(s) }
}

/// Canonical forms:
/// - `KeyCode::Char('=')` for the `=`/`+` physical key
/// - `KeyCode::Tab` for `BackTab` (Shift is added to modifiers)
const fn normalize_code(code: KeyCode) -> KeyCode {
    match code {
        KeyCode::Char('+') => KeyCode::Char('='),
        KeyCode::BackTab => KeyCode::Tab,
        other => other,
    }
}

fn code_label(code: KeyCode) -> String {
    match code {
        KeyCode::Char('=') => "+".to_string(),
        KeyCode::Char(c) => c.to_string(),
        KeyCode::Enter => "Enter".to_string(),
        KeyCode::Esc => "Esc".to_string(),
        KeyCode::Tab | KeyCode::BackTab => "Tab".to_string(),
        KeyCode::Backspace => "Backspace".to_string(),
        KeyCode::Delete => "Delete".to_string(),
        KeyCode::Home => "Home".to_string(),
        KeyCode::End => "End".to_string(),
        KeyCode::Up => "Up".to_string(),
        KeyCode::Down => "Down".to_string(),
        KeyCode::Left => "Left".to_string(),
        KeyCode::Right => "Right".to_string(),
        KeyCode::PageUp => "PageUp".to_string(),
        KeyCode::PageDown => "PageDown".to_string(),
        KeyCode::F(n) => format!("F{n}"),
        _ => format!("{code:?}"),
    }
}

fn parse_keybind(s: &str) -> Result<KeyBind, String> {
    let s = s.trim();
    if s.is_empty() {
        return Err("empty key string".to_string());
    }

    // Bare "+" is the plus/equals key, not a modifier separator.
    if s == "+" || s == "=" {
        return Ok(KeyBind::plain(KeyCode::Char('+')));
    }

    let parts: Vec<&str> = s.split('+').collect();

    // Single-character key with no modifiers: e.g. "q", "/", "-"
    if parts.len() == 1 {
        let code = parse_key_code(parts[0])?;
        return Ok(KeyBind::new(code, KeyModifiers::NONE));
    }

    // Last part is the key, preceding parts are modifiers.
    let (modifier_parts, key_part) = parts.split_at(parts.len() - 1);
    let key_part = key_part[0];

    if key_part.is_empty() {
        return Err(format!("modifier with no key: \"{s}\""));
    }

    let mut modifiers = KeyModifiers::NONE;
    for modifier in modifier_parts {
        match modifier.to_lowercase().as_str() {
            "ctrl" | "control" => modifiers |= KeyModifiers::CONTROL,
            "alt" | "option" => modifiers |= KeyModifiers::ALT,
            "shift" => modifiers |= KeyModifiers::SHIFT,
            other => return Err(format!("unknown modifier: \"{other}\"")),
        }
    }

    let code = parse_key_code(key_part)?;
    Ok(KeyBind::new(code, modifiers))
}

fn parse_key_code(s: &str) -> Result<KeyCode, String> {
    // Named keys (case-insensitive).
    match s.to_lowercase().as_str() {
        "enter" | "return" => return Ok(KeyCode::Enter),
        "esc" | "escape" => return Ok(KeyCode::Esc),
        "tab" => return Ok(KeyCode::Tab),
        "backspace" => return Ok(KeyCode::Backspace),
        "delete" | "del" => return Ok(KeyCode::Delete),
        "home" => return Ok(KeyCode::Home),
        "end" => return Ok(KeyCode::End),
        "up" => return Ok(KeyCode::Up),
        "down" => return Ok(KeyCode::Down),
        "left" => return Ok(KeyCode::Left),
        "right" => return Ok(KeyCode::Right),
        "pageup" => return Ok(KeyCode::PageUp),
        "pagedown" => return Ok(KeyCode::PageDown),
        "space" => return Ok(KeyCode::Char(' ')),
        _ => {},
    }

    // F-keys: "F1" .. "F12".
    if let Some(n) = s.strip_prefix('F').or_else(|| s.strip_prefix('f'))
        && let Ok(n) = n.parse::<u8>()
        && (1..=12).contains(&n)
    {
        return Ok(KeyCode::F(n));
    }

    // Single character.
    let mut chars = s.chars();
    if let Some(c) = chars.next()
        && chars.next().is_none()
    {
        return Ok(KeyCode::Char(c));
    }

    Err(format!("unknown key: \"{s}\""))
}

// ── Action enums ─────────────────────────────────────────────────────

macro_rules! action_enum {
    (
        $(#[$meta:meta])*
        $vis:vis enum $Name:ident {
            $( $Variant:ident => $toml_key:literal, $desc:literal; )*
        }
    ) => {
        $(#[$meta])*
        $vis enum $Name {
            $( $Variant, )*
        }

        impl $Name {
            pub const ALL: &[Self] = &[ $( Self::$Variant, )* ];

            pub const fn toml_key(self) -> &'static str {
                match self {
                    $( Self::$Variant => $toml_key, )*
                }
            }

            pub const fn description(self) -> &'static str {
                match self {
                    $( Self::$Variant => $desc, )*
                }
            }

            pub fn from_toml_key(key: &str) -> Option<Self> {
                match key {
                    $( $toml_key => Some(Self::$Variant), )*
                    _ => None,
                }
            }
        }
    };
}

action_enum! {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum GlobalAction {
        Quit       => "quit",        "Quit application";
        Restart    => "restart",     "Restart application";
        Find       => "find",        "Open finder";
        OpenEditor => "open_editor", "Open in editor";
        OpenTerminal => "open_terminal", "Open terminal";
        Settings   => "settings",    "Open settings";
        NextPane   => "next_pane",   "Focus next pane";
        PrevPane   => "prev_pane",   "Focus previous pane";
        OpenKeymap => "open_keymap", "Open keymap";
        Rescan     => "rescan",      "Rescan projects";
        Dismiss    => "dismiss",     "Dismiss focused item";
    }
}

action_enum! {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum ProjectListAction {
        ExpandAll   => "expand_all",   "Expand all";
        CollapseAll => "collapse_all", "Collapse all";
        Clean       => "clean",        "Clean project";
    }
}

action_enum! {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum PackageAction {
        Activate => "activate", "Open URL or Cargo.toml";
        Clean    => "clean",    "Clean project";
    }
}

action_enum! {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum GitAction {
        Activate => "activate", "Open git URL";
        Clean    => "clean",    "Clean project";
    }
}

action_enum! {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum TargetsAction {
        Activate     => "activate",      "Run in debug mode";
        ReleaseBuild => "release_build", "Run in release mode";
        Clean        => "clean",         "Clean project";
    }
}

action_enum! {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum CiRunsAction {
        Activate   => "activate",    "Open run";
        FetchMore  => "fetch_more",  "Fetch more CI runs";
        ToggleView => "toggle_view", "Toggle branch/all filter";
        ClearCache => "clear_cache", "Clear CI cache";
    }
}

action_enum! {
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub enum LintsAction {
        Activate     => "activate",      "Open lint output";
        ClearHistory => "clear_history", "Clear lint history";
    }
}

// ── Scope map ────────────────────────────────────────────────────────

/// Bidirectional map for a single scope: key→action for dispatch,
/// action→key for display.
#[derive(Clone, Debug)]
pub(crate) struct ScopeMap<A: Copy + Eq + std::hash::Hash> {
    pub by_key:    HashMap<KeyBind, A>,
    pub by_action: HashMap<A, KeyBind>,
}

impl<A: Copy + Eq + std::hash::Hash> ScopeMap<A> {
    pub(crate) fn new() -> Self {
        Self {
            by_key:    HashMap::new(),
            by_action: HashMap::new(),
        }
    }

    pub(crate) fn insert(&mut self, key: KeyBind, action: A) {
        self.by_key.insert(key.clone(), action);
        self.by_action.insert(action, key);
    }

    pub(crate) fn action_for(&self, key: &KeyBind) -> Option<A> { self.by_key.get(key).copied() }

    pub(crate) fn key_for(&self, action: A) -> Option<&KeyBind> { self.by_action.get(&action) }

    /// Display string for an action's bound key, or `"—"` if unbound.
    pub(crate) fn display_key_for(&self, action: A) -> String {
        self.key_for(action)
            .map_or_else(|| "".to_string(), KeyBind::display)
    }
}

impl<A: Copy + Eq + std::hash::Hash> Default for ScopeMap<A> {
    fn default() -> Self { Self::new() }
}

// ── Resolved keymap ──────────────────────────────────────────────────

/// Runtime lookup structure: one `ScopeMap` per scope, built from the
/// TOML config at load time.
#[derive(Clone, Debug, Default)]
pub(crate) struct ResolvedKeymap {
    pub global:       ScopeMap<GlobalAction>,
    pub project_list: ScopeMap<ProjectListAction>,
    pub package:      ScopeMap<PackageAction>,
    pub git:          ScopeMap<GitAction>,
    pub targets:      ScopeMap<TargetsAction>,
    pub ci_runs:      ScopeMap<CiRunsAction>,
    pub lints:        ScopeMap<LintsAction>,
}

impl ResolvedKeymap {
    /// The built-in default keymap matching the current hardcoded bindings.
    pub(crate) fn defaults() -> Self {
        let mut km = Self::default();

        // Global
        km.global
            .insert(KeyBind::plain(KeyCode::Char('q')), GlobalAction::Quit);
        km.global
            .insert(KeyBind::plain(KeyCode::Char('R')), GlobalAction::Restart);
        km.global
            .insert(KeyBind::plain(KeyCode::Char('/')), GlobalAction::Find);
        km.global
            .insert(KeyBind::plain(KeyCode::Char('e')), GlobalAction::OpenEditor);
        km.global.insert(
            KeyBind::plain(KeyCode::Char('t')),
            GlobalAction::OpenTerminal,
        );
        km.global
            .insert(KeyBind::plain(KeyCode::Char('s')), GlobalAction::Settings);
        km.global
            .insert(KeyBind::plain(KeyCode::Tab), GlobalAction::NextPane);
        km.global.insert(
            KeyBind::new(KeyCode::BackTab, KeyModifiers::SHIFT),
            GlobalAction::PrevPane,
        );
        km.global.insert(
            KeyBind::new(KeyCode::Char('k'), KeyModifiers::CONTROL),
            GlobalAction::OpenKeymap,
        );
        km.global.insert(
            KeyBind::new(KeyCode::Char('r'), KeyModifiers::CONTROL),
            GlobalAction::Rescan,
        );
        km.global
            .insert(KeyBind::plain(KeyCode::Char('x')), GlobalAction::Dismiss);

        // Project list
        km.project_list.insert(
            KeyBind::plain(KeyCode::Char('=')),
            ProjectListAction::ExpandAll,
        );
        km.project_list.insert(
            KeyBind::plain(KeyCode::Char('-')),
            ProjectListAction::CollapseAll,
        );
        km.project_list
            .insert(KeyBind::plain(KeyCode::Char('c')), ProjectListAction::Clean);

        // Package
        km.package
            .insert(KeyBind::plain(KeyCode::Enter), PackageAction::Activate);
        km.package
            .insert(KeyBind::plain(KeyCode::Char('c')), PackageAction::Clean);

        // Git
        km.git
            .insert(KeyBind::plain(KeyCode::Enter), GitAction::Activate);
        km.git
            .insert(KeyBind::plain(KeyCode::Char('c')), GitAction::Clean);

        // Targets
        km.targets
            .insert(KeyBind::plain(KeyCode::Enter), TargetsAction::Activate);
        km.targets.insert(
            KeyBind::plain(KeyCode::Char('r')),
            TargetsAction::ReleaseBuild,
        );
        km.targets
            .insert(KeyBind::plain(KeyCode::Char('c')), TargetsAction::Clean);

        // CI runs
        km.ci_runs
            .insert(KeyBind::plain(KeyCode::Enter), CiRunsAction::Activate);
        km.ci_runs
            .insert(KeyBind::plain(KeyCode::Char('f')), CiRunsAction::FetchMore);
        km.ci_runs
            .insert(KeyBind::plain(KeyCode::Char('v')), CiRunsAction::ToggleView);
        km.ci_runs
            .insert(KeyBind::plain(KeyCode::Char('d')), CiRunsAction::ClearCache);

        // Lints
        km.lints
            .insert(KeyBind::plain(KeyCode::Enter), LintsAction::Activate);
        km.lints.insert(
            KeyBind::plain(KeyCode::Char('d')),
            LintsAction::ClearHistory,
        );

        km
    }

    fn write_scope<A: Copy + Eq + std::hash::Hash>(
        out: &mut String,
        header: &str,
        scope: &ScopeMap<A>,
        actions: &[A],
        toml_key: fn(A) -> &'static str,
    ) {
        let _ = writeln!(out, "[{header}]");
        let mut entries: Vec<(&str, String)> = actions
            .iter()
            .map(|&action| {
                let key_str = scope
                    .key_for(action)
                    .map_or_else(String::new, KeyBind::to_toml_string);
                (toml_key(action), key_str)
            })
            .collect();
        entries.sort_by_key(|(name, _)| *name);
        let max_len = entries
            .iter()
            .map(|(name, _)| name.len())
            .max()
            .unwrap_or(0);
        for (name, value) in &entries {
            let _ = writeln!(out, "{name:<max_len$} = \"{value}\"");
        }
        out.push('\n');
    }

    /// Generate the default TOML content for `keymap.toml`.
    pub(crate) fn default_toml() -> String {
        let km = Self::defaults();
        let mut out = String::from(
            "# cargo-port keymap configuration\n\
             # Edit bindings below. Format: action = \"Key\" or \"Modifier+Key\"\n\
             # Modifiers: Ctrl, Alt, Shift.  Examples: \"Ctrl+r\", \"Shift+Tab\", \"q\"\n\
             # Note: = and + are treated as the same physical key.\n\
             # Note: when vim navigation is enabled, h/j/k/l are reserved\n\
             #       for navigation and cannot be used as action keys.\n\n",
        );

        Self::write_all_scopes(&mut out, &km);

        out
    }

    /// Generate TOML content from the given keymap (for saving after UI edits).
    pub(crate) fn default_toml_from(km: &Self) -> String {
        let mut out = String::new();
        Self::write_all_scopes(&mut out, km);
        out
    }

    fn write_all_scopes(out: &mut String, km: &Self) {
        Self::write_scope(
            out,
            "global",
            &km.global,
            GlobalAction::ALL,
            GlobalAction::toml_key,
        );
        Self::write_scope(
            out,
            "project_list",
            &km.project_list,
            ProjectListAction::ALL,
            ProjectListAction::toml_key,
        );
        Self::write_scope(
            out,
            "package",
            &km.package,
            PackageAction::ALL,
            PackageAction::toml_key,
        );
        Self::write_scope(out, "git", &km.git, GitAction::ALL, GitAction::toml_key);
        Self::write_scope(
            out,
            "targets",
            &km.targets,
            TargetsAction::ALL,
            TargetsAction::toml_key,
        );
        Self::write_scope(
            out,
            "ci_runs",
            &km.ci_runs,
            CiRunsAction::ALL,
            CiRunsAction::toml_key,
        );
        Self::write_scope(
            out,
            "lints",
            &km.lints,
            LintsAction::ALL,
            LintsAction::toml_key,
        );
    }
}

// ── Loading & validation ─────────────────────────────────────────────

pub(crate) struct KeymapLoadResult {
    pub keymap:          ResolvedKeymap,
    pub errors:          Vec<KeymapError>,
    pub missing_actions: Vec<String>,
}

pub(crate) struct KeymapError {
    pub scope:  String,
    pub action: String,
    pub key:    String,
    pub reason: KeymapErrorReason,
}

impl fmt::Display for KeymapError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}.{}: \"{}\"{}",
            self.scope, self.action, self.key, self.reason
        )
    }
}

pub(crate) enum KeymapErrorReason {
    ParseError(String),
    ConflictWithGlobal(String),
    ConflictWithinScope(String),
    ReservedForVimMode,
    ReservedForNavigation,
    UnknownAction,
}

impl fmt::Display for KeymapErrorReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ParseError(msg) => write!(f, "parse error: {msg}"),
            Self::ConflictWithGlobal(action) => write!(f, "conflicts with global.{action}"),
            Self::ConflictWithinScope(action) => write!(f, "conflicts with {action}"),
            Self::ReservedForVimMode => write!(f, "reserved for vim navigation"),
            Self::ReservedForNavigation => write!(f, "reserved for navigation"),
            Self::UnknownAction => write!(f, "unknown action (ignored)"),
        }
    }
}

/// Path to the keymap config file.
pub(crate) fn keymap_path() -> Option<AbsolutePath> {
    dirs::config_dir().map(|d| {
        d.join(crate::constants::APP_NAME)
            .join(crate::constants::KEYMAP_FILE)
            .into()
    })
}

/// Load and validate keymap from disk. Creates the default file if missing.
pub(crate) fn load_keymap(vim_mode: NavigationKeys) -> KeymapLoadResult {
    let Some(path) = keymap_path() else {
        return KeymapLoadResult {
            keymap:          ResolvedKeymap::defaults(),
            errors:          Vec::new(),
            missing_actions: Vec::new(),
        };
    };

    if !path.exists() {
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let _ = std::fs::write(&path, ResolvedKeymap::default_toml());
        return KeymapLoadResult {
            keymap:          ResolvedKeymap::defaults(),
            errors:          Vec::new(),
            missing_actions: Vec::new(),
        };
    }

    let contents = match std::fs::read_to_string(&path) {
        Ok(c) => c,
        Err(e) => {
            return KeymapLoadResult {
                keymap:          ResolvedKeymap::defaults(),
                errors:          vec![KeymapError {
                    scope:  String::new(),
                    action: String::new(),
                    key:    String::new(),
                    reason: KeymapErrorReason::ParseError(format!("read error: {e}")),
                }],
                missing_actions: Vec::new(),
            };
        },
    };

    let table: toml::Table = match contents.parse() {
        Ok(t) => t,
        Err(e) => {
            return KeymapLoadResult {
                keymap:          ResolvedKeymap::defaults(),
                errors:          vec![KeymapError {
                    scope:  String::new(),
                    action: String::new(),
                    key:    String::new(),
                    reason: KeymapErrorReason::ParseError(format!("TOML parse error: {e}")),
                }],
                missing_actions: Vec::new(),
            };
        },
    };

    let result = resolve_from_table(&table, vim_mode);

    // Backfill missing entries into the file.
    if !result.missing_actions.is_empty() {
        let content = ResolvedKeymap::default_toml_from(&result.keymap);
        let _ = std::fs::write(&path, content);
    }

    result
}

/// Load keymap from a TOML string (for testing and hot-reload).
pub(crate) fn load_keymap_from_str(toml_str: &str, vim_mode: NavigationKeys) -> KeymapLoadResult {
    let table: toml::Table = match toml_str.parse() {
        Ok(t) => t,
        Err(e) => {
            return KeymapLoadResult {
                keymap:          ResolvedKeymap::defaults(),
                errors:          vec![KeymapError {
                    scope:  String::new(),
                    action: String::new(),
                    key:    String::new(),
                    reason: KeymapErrorReason::ParseError(format!("TOML parse error: {e}")),
                }],
                missing_actions: Vec::new(),
            };
        },
    };
    resolve_from_table(&table, vim_mode)
}

/// Check whether enabling vim mode would conflict with current keymap bindings.
/// Returns the list of conflicting bindings (scope.action = key).
pub(crate) fn vim_mode_conflicts(keymap: &ResolvedKeymap) -> Vec<String> {
    fn check_scope<A: Copy + Eq + std::hash::Hash>(
        scope_name: &str,
        scope: &ScopeMap<A>,
        vim_keys: &[KeyCode; 4],
        toml_key: fn(A) -> &'static str,
        conflicts: &mut Vec<String>,
    ) {
        for (bind, &action) in &scope.by_key {
            if bind.modifiers == KeyModifiers::NONE && vim_keys.contains(&bind.code) {
                conflicts.push(format!("{scope_name}.{}", toml_key(action)));
            }
        }
    }

    let vim_keys: [KeyCode; 4] = [
        KeyCode::Char('h'),
        KeyCode::Char('j'),
        KeyCode::Char('k'),
        KeyCode::Char('l'),
    ];
    let mut conflicts = Vec::new();

    check_scope(
        "global",
        &keymap.global,
        &vim_keys,
        GlobalAction::toml_key,
        &mut conflicts,
    );
    check_scope(
        "project_list",
        &keymap.project_list,
        &vim_keys,
        ProjectListAction::toml_key,
        &mut conflicts,
    );
    check_scope(
        "package",
        &keymap.package,
        &vim_keys,
        PackageAction::toml_key,
        &mut conflicts,
    );
    check_scope(
        "git",
        &keymap.git,
        &vim_keys,
        GitAction::toml_key,
        &mut conflicts,
    );
    check_scope(
        "targets",
        &keymap.targets,
        &vim_keys,
        TargetsAction::toml_key,
        &mut conflicts,
    );
    check_scope(
        "ci_runs",
        &keymap.ci_runs,
        &vim_keys,
        CiRunsAction::toml_key,
        &mut conflicts,
    );
    check_scope(
        "lints",
        &keymap.lints,
        &vim_keys,
        LintsAction::toml_key,
        &mut conflicts,
    );

    conflicts
}

// ── Internal resolution ──────────────────────────────────────────────

const VIM_RESERVED: [KeyCode; 4] = [
    KeyCode::Char('h'),
    KeyCode::Char('j'),
    KeyCode::Char('k'),
    KeyCode::Char('l'),
];

const NAVIGATION_RESERVED: [KeyCode; 6] = [
    KeyCode::Up,
    KeyCode::Down,
    KeyCode::Left,
    KeyCode::Right,
    KeyCode::Home,
    KeyCode::End,
];

fn is_vim_reserved(bind: &KeyBind, vim_mode: NavigationKeys) -> bool {
    vim_mode.uses_vim() && bind.modifiers == KeyModifiers::NONE && VIM_RESERVED.contains(&bind.code)
}

fn is_navigation_reserved(bind: &KeyBind) -> bool {
    bind.modifiers == KeyModifiers::NONE && NAVIGATION_RESERVED.contains(&bind.code)
}

fn is_legacy_removed_action(scope_name: &str, action: &str) -> bool {
    scope_name == "project_list" && matches!(action, "open_editor" | "rescan")
}

fn resolve_from_table(table: &toml::Table, vim_mode: NavigationKeys) -> KeymapLoadResult {
    let defaults = ResolvedKeymap::defaults();
    let mut keymap = ResolvedKeymap::default();
    let mut errors = Vec::new();
    let mut missing_actions = Vec::new();
    let no_globals = HashMap::new();

    // Phase 1: resolve globals (with intra-scope duplicate check).
    let mut ctx = ScopeResolveContext {
        table,
        errors: &mut errors,
        missing_actions: &mut missing_actions,
        global_keys: &no_globals,
        vim_mode,
    };
    resolve_scope(
        &mut ctx,
        "global",
        GlobalAction::ALL,
        GlobalAction::from_toml_key,
        GlobalAction::toml_key,
        &defaults.global,
        &mut keymap.global,
    );

    // Phase 2: resolve each pane scope against the accepted globals.
    let global_keys: HashMap<KeyBind, String> = keymap
        .global
        .by_key
        .iter()
        .map(|(k, &a)| (k.clone(), a.toml_key().to_string()))
        .collect();
    ctx.global_keys = &global_keys;
    resolve_pane_scopes(&mut ctx, &defaults, &mut keymap);

    KeymapLoadResult {
        keymap,
        errors,
        missing_actions,
    }
}

fn resolve_pane_scopes(
    ctx: &mut ScopeResolveContext<'_>,
    defaults: &ResolvedKeymap,
    keymap: &mut ResolvedKeymap,
) {
    resolve_scope(
        ctx,
        "project_list",
        ProjectListAction::ALL,
        ProjectListAction::from_toml_key,
        ProjectListAction::toml_key,
        &defaults.project_list,
        &mut keymap.project_list,
    );
    resolve_scope(
        ctx,
        "package",
        PackageAction::ALL,
        PackageAction::from_toml_key,
        PackageAction::toml_key,
        &defaults.package,
        &mut keymap.package,
    );
    resolve_scope(
        ctx,
        "git",
        GitAction::ALL,
        GitAction::from_toml_key,
        GitAction::toml_key,
        &defaults.git,
        &mut keymap.git,
    );
    resolve_scope(
        ctx,
        "targets",
        TargetsAction::ALL,
        TargetsAction::from_toml_key,
        TargetsAction::toml_key,
        &defaults.targets,
        &mut keymap.targets,
    );
    resolve_scope(
        ctx,
        "ci_runs",
        CiRunsAction::ALL,
        CiRunsAction::from_toml_key,
        CiRunsAction::toml_key,
        &defaults.ci_runs,
        &mut keymap.ci_runs,
    );
    resolve_scope(
        ctx,
        "lints",
        LintsAction::ALL,
        LintsAction::from_toml_key,
        LintsAction::toml_key,
        &defaults.lints,
        &mut keymap.lints,
    );
}

struct ScopeResolveContext<'a> {
    table:           &'a toml::Table,
    errors:          &'a mut Vec<KeymapError>,
    missing_actions: &'a mut Vec<String>,
    global_keys:     &'a HashMap<KeyBind, String>,
    vim_mode:        NavigationKeys,
}

fn resolve_scope<A: Copy + Eq + std::hash::Hash>(
    ctx: &mut ScopeResolveContext<'_>,
    scope_name: &str,
    all_actions: &[A],
    from_toml_key: fn(&str) -> Option<A>,
    to_toml_key: fn(A) -> &'static str,
    defaults: &ScopeMap<A>,
    target: &mut ScopeMap<A>,
) {
    let scope_table = ctx.table.get(scope_name).and_then(toml::Value::as_table);

    // Report unknown keys in this scope.
    if let Some(st) = scope_table {
        for key in st.keys() {
            if from_toml_key(key).is_none() && !is_legacy_removed_action(scope_name, key) {
                ctx.errors.push(KeymapError {
                    scope:  scope_name.to_string(),
                    action: key.clone(),
                    key:    String::new(),
                    reason: KeymapErrorReason::UnknownAction,
                });
            }
        }
    }

    // Resolve each action.
    for &action in all_actions {
        let toml_key = to_toml_key(action);
        let raw_value = scope_table
            .and_then(|st| st.get(toml_key))
            .and_then(toml::Value::as_str);

        let bind_result = raw_value.map(str::parse::<KeyBind>);

        let (bind, error) = match bind_result {
            Some(Ok(bind)) => {
                // Validate the parsed binding.
                if is_navigation_reserved(&bind) {
                    (None, Some(KeymapErrorReason::ReservedForNavigation))
                } else if is_vim_reserved(&bind, ctx.vim_mode) {
                    (None, Some(KeymapErrorReason::ReservedForVimMode))
                } else if let Some(global_action) = ctx.global_keys.get(&bind) {
                    (
                        None,
                        Some(KeymapErrorReason::ConflictWithGlobal(global_action.clone())),
                    )
                } else if let Some(&existing) = target.by_key.get(&bind) {
                    (
                        None,
                        Some(KeymapErrorReason::ConflictWithinScope(
                            to_toml_key(existing).to_string(),
                        )),
                    )
                } else {
                    (Some(bind), None)
                }
            },
            Some(Err(e)) => (None, Some(KeymapErrorReason::ParseError(e))),
            None => {
                // Key missing from TOML — record and use default.
                ctx.missing_actions.push(format!("{scope_name}.{toml_key}"));
                (None, None)
            },
        };

        if let Some(reason) = error {
            ctx.errors.push(KeymapError {
                scope: scope_name.to_string(),
                action: toml_key.to_string(),
                key: raw_value.unwrap_or("").to_string(),
                reason,
            });
        }

        if let Some(bind) = bind {
            target.insert(bind, action);
        } else {
            // Fall back to default binding.
            if let Some(default_bind) = defaults.key_for(action) {
                target.insert(default_bind.clone(), action);
            }
        }
    }
}

// ── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
#[allow(clippy::unwrap_used, reason = "tests")]
mod tests {
    use super::*;

    fn normalize_snapshot(text: &str) -> String {
        let normalized = text.replace("\r\n", "\n");
        normalized.trim_end_matches(['\r', '\n']).to_string()
    }

    #[test]
    fn parse_plain_char() {
        let kb: KeyBind = "q".parse().unwrap();
        assert_eq!(kb.code, KeyCode::Char('q'));
        assert_eq!(kb.modifiers, KeyModifiers::NONE);
    }

    #[test]
    fn parse_named_keys() {
        assert_eq!("Enter".parse::<KeyBind>().unwrap().code, KeyCode::Enter);
        assert_eq!("Esc".parse::<KeyBind>().unwrap().code, KeyCode::Esc);
        assert_eq!("Tab".parse::<KeyBind>().unwrap().code, KeyCode::Tab);
        assert_eq!("Space".parse::<KeyBind>().unwrap().code, KeyCode::Char(' '));
        assert_eq!("F1".parse::<KeyBind>().unwrap().code, KeyCode::F(1));
        assert_eq!("F12".parse::<KeyBind>().unwrap().code, KeyCode::F(12));
    }

    #[test]
    fn parse_ctrl_modifier() {
        let kb: KeyBind = "Ctrl+r".parse().unwrap();
        assert_eq!(kb.code, KeyCode::Char('r'));
        assert!(kb.modifiers.contains(KeyModifiers::CONTROL));
    }

    #[test]
    fn parse_shift_modifier() {
        let kb: KeyBind = "Shift+Tab".parse().unwrap();
        assert_eq!(kb.code, KeyCode::Tab);
        assert!(kb.modifiers.contains(KeyModifiers::SHIFT));
    }

    #[test]
    fn parse_alt_modifier() {
        let kb: KeyBind = "Alt+d".parse().unwrap();
        assert_eq!(kb.code, KeyCode::Char('d'));
        assert!(kb.modifiers.contains(KeyModifiers::ALT));
    }

    #[test]
    fn parse_multiple_modifiers() {
        // Shift+x normalizes to Char('X') with SHIFT stripped.
        let kb: KeyBind = "Ctrl+Shift+x".parse().unwrap();
        assert_eq!(kb.code, KeyCode::Char('X'));
        assert!(kb.modifiers.contains(KeyModifiers::CONTROL));
        assert!(!kb.modifiers.contains(KeyModifiers::SHIFT));
    }

    #[test]
    fn serde_round_trip() {
        let cases = [
            "q",
            "Ctrl+r",
            "Alt+d",
            "Shift+Tab",
            "Enter",
            "Esc",
            "/",
            "-",
        ];
        for input in cases {
            let kb: KeyBind = input.parse().unwrap();
            let serialized = kb.to_toml_string();
            let reparsed: KeyBind = serialized.parse().unwrap();
            assert_eq!(kb, reparsed, "round-trip failed for \"{input}\"");
        }
    }

    #[test]
    fn equals_plus_normalization() {
        let plus: KeyBind = "+".parse().unwrap();
        let equals: KeyBind = "=".parse().unwrap();
        assert_eq!(plus, equals);
    }

    #[test]
    fn uppercase_char_strips_shift() {
        // Crossterm delivers Shift+R as Char('R') + SHIFT.
        // Our normalization strips SHIFT since uppercase encodes it.
        let from_event = KeyBind::new(KeyCode::Char('R'), KeyModifiers::SHIFT);
        let from_toml = KeyBind::plain(KeyCode::Char('R'));
        assert_eq!(from_event, from_toml);
        assert_eq!(from_event.modifiers, KeyModifiers::NONE);
    }

    #[test]
    fn shift_plus_lowercase_becomes_uppercase() {
        // TOML "Shift+r" should match bare "R".
        let shift_r: KeyBind = "Shift+r".parse().unwrap();
        let bare_r: KeyBind = "R".parse().unwrap();
        assert_eq!(shift_r, bare_r);
        assert_eq!(shift_r.code, KeyCode::Char('R'));
        assert_eq!(shift_r.modifiers, KeyModifiers::NONE);
    }

    #[test]
    fn ctrl_shift_letter_keeps_ctrl() {
        // Ctrl+Shift+r → Char('R') + CONTROL (SHIFT stripped).
        let kb = KeyBind::new(
            KeyCode::Char('r'),
            KeyModifiers::CONTROL | KeyModifiers::SHIFT,
        );
        assert_eq!(kb.code, KeyCode::Char('R'));
        assert!(kb.modifiers.contains(KeyModifiers::CONTROL));
        assert!(!kb.modifiers.contains(KeyModifiers::SHIFT));
    }

    #[test]
    fn lowercase_without_shift_unchanged() {
        let kb = KeyBind::plain(KeyCode::Char('r'));
        assert_eq!(kb.code, KeyCode::Char('r'));
        assert_eq!(kb.modifiers, KeyModifiers::NONE);
    }

    #[test]
    fn restart_default_matches_crossterm_event() {
        // The default keymap binds restart to Char('R') with NONE modifiers.
        // Crossterm sends Char('R') with SHIFT. They must match.
        let default_bind = ResolvedKeymap::defaults()
            .global
            .key_for(GlobalAction::Restart)
            .unwrap()
            .clone();
        let crossterm_event = KeyBind::new(KeyCode::Char('R'), KeyModifiers::SHIFT);
        assert_eq!(default_bind, crossterm_event);
    }

    #[test]
    fn display_glyphs() {
        assert_eq!(
            KeyBind::new(KeyCode::Char('r'), KeyModifiers::CONTROL).display(),
            "⌃r"
        );
        assert_eq!(
            KeyBind::new(KeyCode::Char('d'), KeyModifiers::ALT).display(),
            "⌥d"
        );
        assert_eq!(
            KeyBind::new(KeyCode::Tab, KeyModifiers::SHIFT).display(),
            "⇧Tab"
        );
        assert_eq!(KeyBind::plain(KeyCode::Char('q')).display(), "q");
    }

    #[test]
    fn plus_displays_as_plus() {
        let kb = KeyBind::plain(KeyCode::Char('='));
        assert_eq!(kb.display(), "+");
        assert_eq!(kb.to_toml_string(), "+");
    }

    #[test]
    fn parse_errors() {
        assert!("".parse::<KeyBind>().is_err(), "empty string");
        assert!("Ctrl+".parse::<KeyBind>().is_err(), "modifier with no key");
        assert!("Ctrl+Ctrl".parse::<KeyBind>().is_err(), "modifier as key");
    }

    #[test]
    fn valid_edge_cases() {
        assert!("+".parse::<KeyBind>().is_ok(), "plus key");
        assert!("/".parse::<KeyBind>().is_ok(), "slash key");
        assert!("Space".parse::<KeyBind>().is_ok(), "space key");
    }

    #[test]
    fn defaults_scope_map_consistency() {
        fn check<A: Copy + Eq + std::hash::Hash>(scope: &ScopeMap<A>, actions: &[A]) {
            for &action in actions {
                assert!(
                    scope.key_for(action).is_some(),
                    "action missing from by_action"
                );
            }
            for (key, &action) in &scope.by_key {
                assert_eq!(
                    scope.by_action.get(&action),
                    Some(key),
                    "by_key/by_action mismatch"
                );
            }
            assert_eq!(scope.by_key.len(), scope.by_action.len());
        }

        let km = ResolvedKeymap::defaults();
        check(&km.global, GlobalAction::ALL);
        check(&km.project_list, ProjectListAction::ALL);
        check(&km.package, PackageAction::ALL);
        check(&km.git, GitAction::ALL);
        check(&km.targets, TargetsAction::ALL);
        check(&km.ci_runs, CiRunsAction::ALL);
        check(&km.lints, LintsAction::ALL);
    }

    #[test]
    fn default_toml_is_parseable() {
        let toml_str = ResolvedKeymap::default_toml();
        let table: toml::Table = toml_str.parse().unwrap();
        assert!(table.contains_key("global"));
        assert!(table.contains_key("project_list"));
        assert!(table.contains_key("package"));
        assert!(table.contains_key("git"));
        assert!(table.contains_key("targets"));
        assert!(table.contains_key("ci_runs"));
        assert!(table.contains_key("lints"));
    }

    // ── Validation tests ─────────────────────────────────────────────

    #[test]
    fn default_toml_loads_without_errors() {
        let toml_str = ResolvedKeymap::default_toml();
        let result = load_keymap_from_str(&toml_str, NavigationKeys::ArrowsOnly);
        assert!(
            result.errors.is_empty(),
            "errors: {:?}",
            result
                .errors
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn global_global_conflict_detected() {
        let toml = r#"
[global]
quit = "q"
restart = "q"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        assert!(
            result
                .errors
                .iter()
                .any(|e| matches!(e.reason, KeymapErrorReason::ConflictWithinScope(_))),
            "expected intra-scope conflict for duplicate 'q'"
        );
    }

    #[test]
    fn pane_global_conflict_detected() {
        let toml = r#"
[global]
quit = "q"
restart = "Shift+r"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"

[project_list]
clean = "q"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        assert!(
            result
                .errors
                .iter()
                .any(|e| matches!(e.reason, KeymapErrorReason::ConflictWithGlobal(_))),
            "expected conflict with global 'q'"
        );
    }

    #[test]
    fn cross_scope_same_key_is_ok() {
        let toml = r#"
[global]
quit = "q"
restart = "Shift+r"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"

[project_list]
clean = "c"

[ci_runs]
clear_cache = "d"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        assert!(
            !result
                .errors
                .iter()
                .any(|e| !matches!(e.reason, KeymapErrorReason::UnknownAction)),
            "unexpected errors"
        );
    }

    #[test]
    fn vim_mode_reservation() {
        let toml = r#"
[global]
quit = "q"
restart = "Shift+r"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"

[project_list]
clean = "h"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsAndVim);
        assert!(
            result
                .errors
                .iter()
                .any(|e| matches!(e.reason, KeymapErrorReason::ReservedForVimMode)),
            "expected vim reservation error for 'h'"
        );
    }

    #[test]
    fn navigation_key_reserved() {
        let toml = r#"
[global]
quit = "Up"
restart = "Shift+r"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        assert!(
            result
                .errors
                .iter()
                .any(|e| matches!(e.reason, KeymapErrorReason::ReservedForNavigation)),
            "expected navigation reservation error for 'Up'"
        );
    }

    #[test]
    fn navigation_key_with_modifier_allowed() {
        let toml = r#"
[global]
quit = "Ctrl+Up"
restart = "Shift+r"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        assert!(
            !result
                .errors
                .iter()
                .any(|e| matches!(e.reason, KeymapErrorReason::ReservedForNavigation)),
            "Ctrl+Up should be allowed"
        );
    }

    #[test]
    fn vim_mode_allows_modified_hjkl() {
        let toml = r#"
[global]
quit = "q"
restart = "Shift+r"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
focus_list = "Esc"
open_keymap = "Ctrl+h"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsAndVim);
        assert!(
            !result
                .errors
                .iter()
                .any(|e| matches!(e.reason, KeymapErrorReason::ReservedForVimMode)),
            "Ctrl+h should be allowed even with vim mode"
        );
    }

    #[test]
    fn unknown_action_reported() {
        let toml = r#"
[project_list]
claen = "c"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        let unknown: Vec<_> = result
            .errors
            .iter()
            .filter(|e| matches!(e.reason, KeymapErrorReason::UnknownAction))
            .collect();
        assert!(
            !unknown.is_empty(),
            "expected unknown action for typo 'claen'"
        );
        assert_eq!(unknown[0].action, "claen");
    }

    #[test]
    fn legacy_project_list_open_editor_is_ignored() {
        let toml = r#"
[global]
quit = "q"
restart = "R"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"
rescan = "r"
dismiss = "x"

[project_list]
open_editor = "Enter"
expand_all = "="
collapse_all = "-"
clean = "c"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        assert!(
            result
                .errors
                .iter()
                .all(|e| !matches!(e.reason, KeymapErrorReason::UnknownAction)),
            "legacy project_list.open_editor should not be reported as unknown: {:?}",
            result
                .errors
                .iter()
                .map(ToString::to_string)
                .collect::<Vec<_>>()
        );
        assert!(
            result
                .missing_actions
                .iter()
                .any(|action| action == "global.open_editor"),
            "new global.open_editor should be backfilled"
        );
        assert_eq!(
            result.keymap.global.key_for(GlobalAction::OpenEditor),
            Some(&KeyBind::plain(KeyCode::Char('e')))
        );
    }

    #[test]
    fn partial_acceptance_valid_bindings_applied() {
        let toml = r#"
[global]
quit = "x"
restart = "x"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        // quit = "x" should be accepted
        assert_eq!(
            result.keymap.global.key_for(GlobalAction::Quit),
            Some(&KeyBind::plain(KeyCode::Char('x')))
        );
        // restart = "x" conflicts with quit, should fall back to default
        assert!(
            result
                .keymap
                .global
                .key_for(GlobalAction::Restart)
                .is_some(),
            "restart should have a fallback binding"
        );
        assert!(!result.errors.is_empty());
    }

    #[test]
    fn malformed_toml_returns_defaults() {
        let result = load_keymap_from_str("{{invalid toml", NavigationKeys::ArrowsOnly);
        assert!(!result.errors.is_empty());
        // Should have defaults for all actions.
        assert!(result.keymap.global.key_for(GlobalAction::Quit).is_some());
    }

    #[test]
    fn vim_mode_conflicts_detected() {
        let defaults = ResolvedKeymap::defaults();
        let conflicts = vim_mode_conflicts(&defaults);
        // Default keymap doesn't use bare hjkl.
        assert!(conflicts.is_empty());

        // Build a keymap with 'h' bound.
        let toml = r#"
[global]
quit = "q"
restart = "Shift+r"
find = "/"
settings = "h"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        let conflicts = vim_mode_conflicts(&result.keymap);
        assert!(!conflicts.is_empty(), "expected conflict for 'h' binding");
    }

    #[test]
    fn action_description_and_display_key() {
        assert_eq!(GlobalAction::Quit.description(), "Quit application");
        let km = ResolvedKeymap::defaults();
        assert_eq!(km.global.display_key_for(GlobalAction::Quit), "q");
        assert_eq!(km.global.display_key_for(GlobalAction::OpenEditor), "e");
        assert_eq!(km.global.display_key_for(GlobalAction::OpenTerminal), "t");
        assert_eq!(km.ci_runs.display_key_for(CiRunsAction::ToggleView), "v");
        assert_eq!(km.global.display_key_for(GlobalAction::OpenKeymap), "⌃k");
    }

    #[test]
    fn legacy_ci_runs_t_conflicts_with_global_terminal_and_falls_back_to_v() {
        let toml = r#"
[global]
quit = "q"
restart = "R"
find = "/"
open_editor = "e"
open_terminal = "t"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
dismiss = "x"
open_keymap = "Ctrl+k"

[ci_runs]
activate = "Enter"
toggle_view = "t"
clear_cache = "d"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);

        assert!(
            result.errors.iter().any(|error| {
                error.scope == "ci_runs"
                    && error.action == "toggle_view"
                    && matches!(error.reason, KeymapErrorReason::ConflictWithGlobal(_))
            }),
            "expected ci_runs.toggle_view conflict with global terminal"
        );
        assert_eq!(
            result.keymap.global.key_for(GlobalAction::OpenTerminal),
            Some(&KeyBind::plain(KeyCode::Char('t')))
        );
        assert_eq!(
            result.keymap.ci_runs.key_for(CiRunsAction::ToggleView),
            Some(&KeyBind::plain(KeyCode::Char('v')))
        );
    }

    #[test]
    fn missing_action_detected() {
        // Omit `quit` from globals — should appear in missing_actions.
        let toml = r#"
[global]
restart = "R"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
open_keymap = "Ctrl+k"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        assert!(
            result.missing_actions.iter().any(|m| m == "global.quit"),
            "expected global.quit in missing_actions: {:?}",
            result.missing_actions
        );
        // Default should still be applied.
        assert_eq!(
            result.keymap.global.key_for(GlobalAction::Quit),
            Some(&KeyBind::plain(KeyCode::Char('q')))
        );
    }

    #[test]
    fn complete_keymap_has_no_missing() {
        let toml_str = ResolvedKeymap::default_toml();
        let result = load_keymap_from_str(&toml_str, NavigationKeys::ArrowsOnly);
        assert!(
            result.missing_actions.is_empty(),
            "default toml should have no missing actions: {:?}",
            result.missing_actions
        );
    }

    #[test]
    fn default_keymap_template_matches_golden_file() {
        let generated = ResolvedKeymap::default_toml();
        let expected = include_str!("../tests/assets/default-keymap.toml");

        assert_eq!(normalize_snapshot(&generated), normalize_snapshot(expected));
    }

    #[test]
    fn missing_entire_scope_detected() {
        // No [lints] section at all — its actions should appear in missing.
        let toml = r#"
[global]
quit = "q"
restart = "R"
find = "/"
settings = "s"
next_pane = "Tab"
prev_pane = "Shift+Tab"
dismiss = "x"
open_keymap = "Ctrl+k"
"#;
        let result = load_keymap_from_str(toml, NavigationKeys::ArrowsOnly);
        assert!(
            result
                .missing_actions
                .iter()
                .any(|m| m.starts_with("lints.")),
            "expected lints actions in missing: {:?}",
            result.missing_actions
        );
    }
}