nut-shell 0.1.2

A lightweight command-line interface library for embedded systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
//! Shell orchestration and command processing.
//!
//! Brings together I/O, command trees, authentication, and history into interactive CLI.
//! Follows unified architecture: single code path handles both auth-enabled and auth-disabled modes.
//! Lifecycle: `Inactive` → `activate()` → (`LoggedOut` →) `LoggedIn` → `deactivate()`.

use crate::auth::{AccessLevel, User};
use crate::config::ShellConfig;
use crate::error::CliError;
use crate::io::CharIo;
use crate::response::Response;
use crate::tree::{CommandKind, Directory, Node};
use core::marker::PhantomData;

#[cfg(feature = "completion")]
use crate::tree::completion::suggest_completions;

// Sub-modules
pub mod decoder;
pub mod handler;
pub mod history;

// Re-export key types
pub use decoder::{InputDecoder, InputEvent};
pub use handler::CommandHandler;
pub use history::CommandHistory;

/// History navigation direction.
///
/// Used by `Request::History` variant. Self-documenting alternative to bool.
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum HistoryDirection {
    /// Up arrow key (navigate to older command)
    Previous = 0,

    /// Down arrow key (navigate to newer command or restore original)
    Next = 1,
}

/// CLI state (authentication state).
///
/// Tracks whether the CLI is active and whether user is authenticated.
/// Used by unified architecture pattern to drive behavior.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum CliState {
    /// CLI not active
    Inactive,

    /// Awaiting authentication
    #[cfg(feature = "authentication")]
    LoggedOut,

    /// Authenticated or auth-disabled mode
    LoggedIn,
}

/// Request type representing parsed user input.
///
/// Generic over `C: ShellConfig` to use configured buffer sizes.
/// Variants are feature-gated based on available features.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Request<C: ShellConfig> {
    /// Valid authentication attempt
    #[cfg(feature = "authentication")]
    Login {
        /// Username
        username: heapless::String<32>,
        /// Password
        password: heapless::String<64>,
    },

    /// Invalid authentication attempt
    #[cfg(feature = "authentication")]
    InvalidLogin,

    /// Execute command
    Command {
        /// Command path
        path: heapless::String<128>, // TODO: Use C::MAX_INPUT when const generics stabilize
        /// Command arguments
        args: heapless::Vec<heapless::String<128>, 16>, // TODO: Use C::MAX_INPUT and C::MAX_ARGS
        /// Original command string for history
        #[cfg(feature = "history")]
        original: heapless::String<128>, // TODO: Use C::MAX_INPUT
        /// Phantom data for config type (will be used when const generics stabilize)
        _phantom: PhantomData<C>,
    },

    /// Request completions
    #[cfg(feature = "completion")]
    TabComplete {
        /// Partial path to complete
        path: heapless::String<128>, // TODO: Use C::MAX_INPUT
    },

    /// Navigate history
    #[cfg(feature = "history")]
    History {
        /// Navigation direction
        direction: HistoryDirection,
        /// Current buffer content
        buffer: heapless::String<128>, // TODO: Use C::MAX_INPUT
    },
}

/// Shell orchestration struct.
///
/// Brings together all components following the unified architecture pattern.
/// Uses single code path for both auth-enabled and auth-disabled modes.
pub struct Shell<'tree, L, IO, H, C>
where
    L: AccessLevel,
    IO: CharIo,
    H: CommandHandler<C>,
    C: ShellConfig,
{
    /// Command tree root
    tree: &'tree Directory<L>,

    /// Current user (None when logged out or auth disabled)
    current_user: Option<User<L>>,

    /// CLI state (auth state)
    state: CliState,

    /// Input buffer (using concrete size for now - TODO: use C::MAX_INPUT when const generics stabilize)
    input_buffer: heapless::String<128>,

    /// Current directory path (stack of child indices, using concrete size - TODO: use C::MAX_PATH_DEPTH when const generics stabilize)
    current_path: heapless::Vec<usize, 8>,

    /// Input decoder (escape sequence state machine)
    decoder: InputDecoder,

    /// Command history (using concrete sizes - TODO: use C::HISTORY_SIZE and C::MAX_INPUT when const generics stabilize)
    #[cfg_attr(not(feature = "history"), allow(dead_code))]
    history: CommandHistory<10, 128>,

    /// I/O interface
    io: IO,

    /// Command handler
    handler: H,

    /// Credential provider
    #[cfg(feature = "authentication")]
    credential_provider: &'tree (dyn crate::auth::CredentialProvider<L, Error = ()> + 'tree),

    /// Config type marker (zero-size)
    _config: PhantomData<C>,
}

// ============================================================================
// Debug implementation
// ============================================================================

impl<'tree, L, IO, H, C> core::fmt::Debug for Shell<'tree, L, IO, H, C>
where
    L: AccessLevel,
    IO: CharIo,
    H: CommandHandler<C>,
    C: ShellConfig,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let mut debug_struct = f.debug_struct("Shell");
        debug_struct
            .field("state", &self.state)
            .field("input_buffer", &self.input_buffer.as_str())
            .field("current_path", &self.current_path);

        if let Some(user) = &self.current_user {
            debug_struct.field("current_user", &user.username.as_str());
        } else {
            debug_struct.field("current_user", &"None");
        }

        #[cfg(feature = "authentication")]
        debug_struct.field("credential_provider", &"<dyn CredentialProvider>");

        debug_struct.finish_non_exhaustive()
    }
}

// ============================================================================
// Constructors (feature-conditional)
// ============================================================================

#[cfg(feature = "authentication")]
impl<'tree, L, IO, H, C> Shell<'tree, L, IO, H, C>
where
    L: AccessLevel,
    IO: CharIo,
    H: CommandHandler<C>,
    C: ShellConfig,
{
    /// Create shell with authentication enabled (starts `Inactive`).
    /// Call `activate()` to show welcome message and login prompt.
    pub fn new(
        tree: &'tree Directory<L>,
        handler: H,
        credential_provider: &'tree (dyn crate::auth::CredentialProvider<L, Error = ()> + 'tree),
        io: IO,
    ) -> Self {
        Self {
            tree,
            handler,
            current_user: None,
            state: CliState::Inactive,
            input_buffer: heapless::String::new(),
            current_path: heapless::Vec::new(),
            decoder: InputDecoder::new(),
            history: CommandHistory::new(),
            io,
            credential_provider,
            _config: PhantomData,
        }
    }
}

#[cfg(not(feature = "authentication"))]
impl<'tree, L, IO, H, C> Shell<'tree, L, IO, H, C>
where
    L: AccessLevel,
    IO: CharIo,
    H: CommandHandler<C>,
    C: ShellConfig,
{
    /// Create new Shell
    ///
    /// Starts in `Inactive` state. Call `activate()` to show welcome message and prompt.
    pub fn new(tree: &'tree Directory<L>, handler: H, io: IO) -> Self {
        Self {
            tree,
            handler,
            current_user: None,
            state: CliState::Inactive,
            input_buffer: heapless::String::new(),
            current_path: heapless::Vec::new(),
            decoder: InputDecoder::new(),
            history: CommandHistory::new(),
            io,
            _config: PhantomData,
        }
    }
}

// ============================================================================
// Core methods (unified implementation for both modes)
// ============================================================================

impl<'tree, L, IO, H, C> Shell<'tree, L, IO, H, C>
where
    L: AccessLevel,
    IO: CharIo,
    H: CommandHandler<C>,
    C: ShellConfig,
{
    /// Activate the shell (show welcome message and initial prompt).
    ///
    /// Transitions from `Inactive` to appropriate state (LoggedOut or LoggedIn).
    pub fn activate(&mut self) -> Result<(), IO::Error> {
        self.io.write_str(C::MSG_WELCOME)?;
        self.io.write_str("\r\n")?;

        #[cfg(feature = "authentication")]
        {
            self.state = CliState::LoggedOut;
            self.io.write_str(C::MSG_LOGIN_PROMPT)?;
        }

        #[cfg(not(feature = "authentication"))]
        {
            self.state = CliState::LoggedIn;
            self.generate_and_write_prompt()?;
        }

        Ok(())
    }

    /// Deactivate shell (transition to `Inactive`).
    /// Clears session and resets to root directory.
    pub fn deactivate(&mut self) {
        self.state = CliState::Inactive;
        self.current_user = None;
        self.input_buffer.clear();
        self.current_path.clear();
    }

    /// Process single character of input (main entry point for char-by-char processing).
    pub fn process_char(&mut self, c: char) -> Result<(), IO::Error> {
        // Decode character into logical event
        let event = self.decoder.decode_char(c);

        match event {
            InputEvent::None => Ok(()), // Still accumulating sequence

            InputEvent::Char(ch) => {
                // Try to add to buffer
                match self.input_buffer.push(ch) {
                    Ok(_) => {
                        // Successfully added - echo (with password masking if applicable)
                        let echo_char = self.get_echo_char(ch);
                        self.io.put_char(echo_char)?;
                        Ok(())
                    }
                    Err(_) => {
                        // Buffer full - beep and ignore
                        self.io.put_char('\x07')?; // Bell character
                        Ok(())
                    }
                }
            }

            InputEvent::Backspace => {
                // Remove from buffer if not empty
                if !self.input_buffer.is_empty() {
                    self.input_buffer.pop();
                    // Echo backspace sequence
                    self.io.write_str("\x08 \x08")?;
                }
                Ok(())
            }

            InputEvent::DoubleEsc => {
                // Clear buffer and redraw (Shell's interpretation of double-ESC)
                self.input_buffer.clear();
                self.clear_line_and_redraw()
            }

            InputEvent::Enter => self.handle_enter(),

            InputEvent::Tab => self.handle_tab(),

            InputEvent::UpArrow => self.handle_history(HistoryDirection::Previous),

            InputEvent::DownArrow => self.handle_history(HistoryDirection::Next),
        }
    }

    /// Process single character of input (async version).
    /// Can execute both sync and async commands.
    #[cfg(feature = "async")]
    pub async fn process_char_async(&mut self, c: char) -> Result<(), IO::Error> {
        // Decode character into logical event
        let event = self.decoder.decode_char(c);

        match event {
            InputEvent::None => Ok(()), // Still accumulating sequence

            InputEvent::Char(ch) => {
                // Try to add to buffer
                match self.input_buffer.push(ch) {
                    Ok(_) => {
                        // Successfully added - echo (with password masking if applicable)
                        let echo_char = self.get_echo_char(ch);
                        self.io.put_char(echo_char)?;
                        Ok(())
                    }
                    Err(_) => {
                        // Buffer full - beep and ignore
                        self.io.put_char('\x07')?; // Bell character
                        Ok(())
                    }
                }
            }

            InputEvent::Backspace => {
                // Remove from buffer if not empty
                if !self.input_buffer.is_empty() {
                    self.input_buffer.pop();
                    // Echo backspace sequence
                    self.io.write_str("\x08 \x08")?;
                }
                Ok(())
            }

            InputEvent::DoubleEsc => {
                // Clear buffer and redraw (Shell's interpretation of double-ESC)
                self.input_buffer.clear();
                self.clear_line_and_redraw()
            }

            InputEvent::Enter => self.handle_enter_async().await,

            InputEvent::Tab => self.handle_tab(),

            InputEvent::UpArrow => self.handle_history(HistoryDirection::Previous),

            InputEvent::DownArrow => self.handle_history(HistoryDirection::Next),
        }
    }

    /// Poll for incoming characters and process them.
    /// For interrupt-driven/DMA/async/RTOS use `process_char()` directly.
    pub fn poll(&mut self) -> Result<(), IO::Error> {
        if let Some(c) = self.io.get_char()? {
            self.process_char(c)?;
        }
        Ok(())
    }

    /// Determine what character to echo based on password masking rules.
    ///
    /// During login, masks characters after `:` delimiter with `*` for password privacy.
    fn get_echo_char(&self, ch: char) -> char {
        #[cfg(feature = "authentication")]
        {
            // Password masking only applies during login (LoggedOut state)
            if self.state == CliState::LoggedOut {
                // Count colons in buffer (parser has already added current char)
                let colon_count = self.input_buffer.matches(':').count();

                // Logic: Mask if buffer had at least one colon before this character
                // - colon_count == 0: No delimiter yet, echo normally
                // - colon_count == 1 && ch == ':': First colon (just added), echo normally
                // - Otherwise: We're in password territory, mask it
                if colon_count == 0 || (colon_count == 1 && ch == ':') {
                    return ch; // Username or delimiter
                } else {
                    return '*'; // Password
                }
            }
        }

        // Default: echo character as-is
        ch
    }

    /// Generate prompt string.
    ///
    /// Format: `username@path> ` (or `@path> ` when no user/auth disabled)
    // TODO: Use C::MAX_PROMPT when const generics stabilize
    fn generate_prompt(&self) -> heapless::String<128> {
        let mut prompt = heapless::String::new();

        // Username part
        if let Some(user) = &self.current_user {
            prompt.push_str(user.username.as_str()).ok();
        }
        prompt.push('@').ok();

        // Path part
        prompt.push('/').ok();
        if !self.current_path.is_empty()
            && let Ok(path_str) = self.get_current_path_string()
        {
            prompt.push_str(&path_str).ok();
        }

        prompt.push_str("> ").ok();
        prompt
    }

    /// Write prompt to I/O.
    fn generate_and_write_prompt(&mut self) -> Result<(), IO::Error> {
        let prompt = self.generate_prompt();
        self.io.write_str(prompt.as_str())
    }

    /// Write formatted response to I/O, applying Response formatting flags.
    ///
    /// Applies `prefix_newline`, `indent_message`, and `postfix_newline` flags.
    /// Note: `inline_message` and `show_prompt` are handled by callers.
    fn write_formatted_response(&mut self, response: &Response<C>) -> Result<(), IO::Error> {
        // Prefix newline (blank line before output)
        if response.prefix_newline {
            self.io.write_str("\r\n")?;
        }

        // Write message (with optional indentation)
        if response.indent_message {
            // Split by lines and indent each
            for (i, line) in response.message.split("\r\n").enumerate() {
                if i > 0 {
                    self.io.write_str("\r\n")?;
                }
                self.io.write_str("  ")?; // 2-space indent
                self.io.write_str(line)?;
            }
        } else {
            // Write message as-is
            self.io.write_str(&response.message)?;
        }

        // Postfix newline
        if response.postfix_newline {
            self.io.write_str("\r\n")?;
        }

        Ok(())
    }

    /// Format error message using Display trait.
    ///
    /// Converts CliError to a heapless string using its Display implementation.
    /// Returns a buffer containing the formatted error message.
    // TODO: Use C::MAX_RESPONSE when const generics stabilize
    fn format_error(error: &CliError) -> heapless::String<256> {
        use core::fmt::Write;
        let mut buffer = heapless::String::new();
        // Write using Display trait implementation
        // Ignore write errors (buffer full) - partial message is better than none
        let _ = write!(&mut buffer, "{}", error);
        buffer
    }

    /// Get current directory node.
    fn get_current_dir(&self) -> Result<&'tree Directory<L>, CliError> {
        let mut current: &Directory<L> = self.tree;

        for &index in self.current_path.iter() {
            match current.children.get(index) {
                Some(Node::Directory(dir)) => current = dir,
                Some(Node::Command(_)) | None => return Err(CliError::InvalidPath),
            }
        }

        Ok(current)
    }

    /// Get current path as string (for prompt).
    // TODO: Use C::MAX_INPUT when const generics stabilize
    fn get_current_path_string(&self) -> Result<heapless::String<128>, CliError> {
        let mut path_str = heapless::String::new();
        let mut current: &Directory<L> = self.tree;

        for (i, &index) in self.current_path.iter().enumerate() {
            match current.children.get(index) {
                Some(Node::Directory(dir)) => {
                    if i > 0 {
                        path_str.push('/').map_err(|_| CliError::BufferFull)?;
                    }
                    path_str
                        .push_str(dir.name)
                        .map_err(|_| CliError::BufferFull)?;
                    current = dir;
                }
                _ => return Err(CliError::InvalidPath),
            }
        }

        Ok(path_str)
    }

    /// Handle Enter key (submit command or login).
    fn handle_enter(&mut self) -> Result<(), IO::Error> {
        // Note: Newline after input is written by the handler
        // (conditionally based on Response.inline_message flag for commands)

        let input = self.input_buffer.clone();
        self.input_buffer.clear();

        match self.state {
            CliState::Inactive => Ok(()),

            #[cfg(feature = "authentication")]
            CliState::LoggedOut => self.handle_login_input(&input),

            CliState::LoggedIn => self.handle_input_line(&input),
        }
    }

    /// Handle Enter key press - async version.
    ///
    /// Dispatches to appropriate handler based on current state.
    #[cfg(feature = "async")]
    async fn handle_enter_async(&mut self) -> Result<(), IO::Error> {
        // Note: Newline after input is written by the handler
        // (conditionally based on Response.inline_message flag for commands)

        let input = self.input_buffer.clone();
        self.input_buffer.clear();

        match self.state {
            CliState::Inactive => Ok(()),

            #[cfg(feature = "authentication")]
            CliState::LoggedOut => self.handle_login_input(&input),

            CliState::LoggedIn => self.handle_input_line_async(&input).await,
        }
    }

    /// Handle a valid login attempt.
    #[cfg(feature = "authentication")]
    fn handle_login_input(&mut self, input: &str) -> Result<(), IO::Error> {
        // Login doesn't support inline mode - always add newline
        self.io.write_str("\r\n  ")?;

        if input.contains(':') {
            // Format: username:password
            let parts: heapless::Vec<&str, 2> = input.splitn(2, ':').collect();
            if parts.len() == 2 {
                let username = parts[0];
                let password = parts[1];

                // Attempt authentication
                match self.credential_provider.find_user(username) {
                    Ok(Some(user)) if self.credential_provider.verify_password(&user, password) => {
                        // Login successful
                        self.current_user = Some(user);
                        self.state = CliState::LoggedIn;
                        self.io.write_str(C::MSG_LOGIN_SUCCESS)?;
                        self.io.write_str("\r\n")?;
                        self.generate_and_write_prompt()?;
                    }
                    _ => {
                        // Login failed (user not found or wrong password)
                        self.io.write_str(C::MSG_LOGIN_FAILED)?;
                        self.io.write_str("\r\n")?;
                        self.io.write_str(C::MSG_LOGIN_PROMPT)?;
                    }
                }
            } else {
                self.io.write_str(C::MSG_INVALID_LOGIN_FORMAT)?;
                self.io.write_str("\r\n")?;
                self.io.write_str(C::MSG_LOGIN_PROMPT)?;
            }
        } else {
            // No colon - invalid format, show error
            self.io.write_str(C::MSG_INVALID_LOGIN_FORMAT)?;
            self.io.write_str("\r\n")?;
            self.io.write_str(C::MSG_LOGIN_PROMPT)?;
        }

        Ok(())
    }

    /// Process global commands (?, ls, clear, logout).
    ///
    /// Returns true if a global command was handled, false otherwise.
    fn handle_global_commands(&mut self, input: &str) -> Result<bool, IO::Error> {
        // Check for global commands first (non-tree operations)
        // Global commands don't support inline mode
        match input.trim() {
            "?" => {
                self.io.write_str("\r\n")?;
                self.show_help()?;
                self.generate_and_write_prompt()?;
                Ok(true)
            }
            "ls" => {
                self.io.write_str("\r\n")?;
                self.show_ls()?;
                self.generate_and_write_prompt()?;
                Ok(true)
            }
            "clear" => {
                // Clear screen - no newline needed before ANSI clear sequence
                self.io.write_str("\x1b[2J\x1b[H")?; // ANSI clear screen
                self.generate_and_write_prompt()?;
                Ok(true)
            }
            #[cfg(feature = "authentication")]
            "logout" => {
                self.io.write_str("\r\n  ")?;
                self.current_user = None;
                self.state = CliState::LoggedOut;
                self.current_path.clear();
                self.io.write_str(C::MSG_LOGOUT)?;
                self.io.write_str("\r\n")?;
                self.io.write_str(C::MSG_LOGIN_PROMPT)?;
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    /// Write response and handle history/prompt based on Response flags.
    fn write_response_and_prompt(
        &mut self,
        response: Response<C>,
        #[cfg_attr(not(feature = "history"), allow(unused_variables))] input: &str,
    ) -> Result<(), IO::Error> {
        // Add newline after input UNLESS response wants inline mode
        if !response.inline_message {
            self.io.write_str("\r\n")?;
        }

        // Write formatted response (implements all Response flags!)
        self.write_formatted_response(&response)?;

        // Add to history if not excluded
        #[cfg(feature = "history")]
        if !response.exclude_from_history {
            self.history.add(input);
        }

        // Show prompt if requested by response
        if response.show_prompt {
            self.generate_and_write_prompt()?;
        }

        Ok(())
    }

    /// Write error message with formatting.
    fn write_error_and_prompt(&mut self, error: CliError) -> Result<(), IO::Error> {
        // Errors don't support inline mode - add newline
        self.io.write_str("\r\n  ")?;

        // Format and write error message using Display trait
        self.io.write_str("Error: ")?;
        let error_msg = Self::format_error(&error);
        self.io.write_str(error_msg.as_str())?;
        self.io.write_str("\r\n")?;
        self.generate_and_write_prompt()?;

        Ok(())
    }

    /// Handle user input line when in LoggedIn state.
    ///
    /// Processes three types of input:
    /// 1. Global commands (?, ls, clear, logout)
    /// 2. Tree navigation (paths resolving to directories)
    /// 3. Tree commands (paths resolving to Node::Command)
    fn handle_input_line(&mut self, input: &str) -> Result<(), IO::Error> {
        // Skip empty input
        if input.trim().is_empty() {
            self.io.write_str("\r\n")?;
            self.generate_and_write_prompt()?;
            return Ok(());
        }

        // Check for global commands first (non-tree operations)
        if self.handle_global_commands(input)? {
            return Ok(());
        }

        // Handle tree operations (navigation or command execution)
        match self.execute_tree_path(input) {
            Ok(response) => self.write_response_and_prompt(response, input),
            Err(e) => self.write_error_and_prompt(e),
        }
    }

    /// Handle user input line when in LoggedIn state - async version.
    ///
    /// Processes three types of input:
    /// 1. Global commands (?, ls, clear, logout)
    /// 2. Tree navigation (paths resolving to directories)
    /// 3. Tree commands (paths resolving to Node::Command - both sync and async)
    #[cfg(feature = "async")]
    async fn handle_input_line_async(&mut self, input: &str) -> Result<(), IO::Error> {
        // Skip empty input
        if input.trim().is_empty() {
            self.io.write_str("\r\n")?;
            self.generate_and_write_prompt()?;
            return Ok(());
        }

        // Check for global commands first (non-tree operations)
        if self.handle_global_commands(input)? {
            return Ok(());
        }

        // Handle tree operations (navigation or command execution) - async version
        match self.execute_tree_path_async(input).await {
            Ok(response) => self.write_response_and_prompt(response, input),
            Err(e) => self.write_error_and_prompt(e),
        }
    }

    /// Execute a tree path (navigation or command execution).
    ///
    /// Resolves the path and either:
    /// - Navigates to a directory (if path resolves to Node::Directory)
    /// - Executes a tree command (if path resolves to Node::Command)
    ///
    /// Note: "command" here refers specifically to Node::Command,
    /// not generic user input.
    fn execute_tree_path(&mut self, input: &str) -> Result<Response<C>, CliError> {
        // Parse path and arguments
        // TODO: Use C::MAX_ARGS + 1 when const generics stabilize (command + args)
        let parts: heapless::Vec<&str, 17> = input.split_whitespace().collect();
        if parts.is_empty() {
            return Err(CliError::CommandNotFound);
        }

        let path_str = parts[0];
        let args = &parts[1..];

        // Resolve path to node (None represents root directory)
        let (target_node, new_path) = self.resolve_path(path_str)?;

        // Case 1: Directory navigation
        match target_node {
            None | Some(Node::Directory(_)) => {
                if !args.is_empty() {
                    return Err(CliError::InvalidArgumentCount {
                        expected_min: 0,
                        expected_max: 0,
                        received: args.len(),
                    });
                }
                // Directory navigation - update path and return
                self.current_path = new_path;
                #[cfg(feature = "history")]
                return Ok(Response::success("")
                    .without_history()
                    .without_postfix_newline());
                #[cfg(not(feature = "history"))]
                return Ok(Response::success("").without_postfix_newline());
            }
            Some(Node::Command(cmd_meta)) => {
                // Case 2: Tree command execution
                // Check access control - use InvalidPath for security (don't reveal access denied)
                if let Some(user) = &self.current_user
                    && user.access_level < cmd_meta.access_level
                {
                    return Err(CliError::InvalidPath);
                }

                // Validate argument count
                if args.len() < cmd_meta.min_args || args.len() > cmd_meta.max_args {
                    return Err(CliError::InvalidArgumentCount {
                        expected_min: cmd_meta.min_args,
                        expected_max: cmd_meta.max_args,
                        received: args.len(),
                    });
                }

                // Dispatch to command handler
                match cmd_meta.kind {
                    CommandKind::Sync => {
                        // Execute synchronous tree command (dispatch by unique ID)
                        self.handler.execute_sync(cmd_meta.id, args)
                    }
                    #[cfg(feature = "async")]
                    CommandKind::Async => {
                        // Async tree command called from sync context
                        Err(CliError::AsyncInSyncContext)
                    }
                }
            }
        }
    }

    /// Execute a tree path (navigation or command execution) - async version.
    ///
    /// Resolves the path and either:
    /// - Navigates to a directory (if path resolves to Node::Directory)
    /// - Executes a tree command (if path resolves to Node::Command)
    ///
    /// This async version can execute both sync and async commands.
    /// Sync commands are called directly, async commands are awaited.
    ///
    /// Note: "command" here refers specifically to Node::Command,
    /// not generic user input.
    #[cfg(feature = "async")]
    async fn execute_tree_path_async(&mut self, input: &str) -> Result<Response<C>, CliError> {
        // Parse path and arguments
        // TODO: Use C::MAX_ARGS + 1 when const generics stabilize (command + args)
        let parts: heapless::Vec<&str, 17> = input.split_whitespace().collect();
        if parts.is_empty() {
            return Err(CliError::CommandNotFound);
        }

        let path_str = parts[0];
        let args = &parts[1..];

        // Resolve path to node (None represents root directory)
        let (target_node, new_path) = self.resolve_path(path_str)?;

        // Case 1: Directory navigation
        match target_node {
            None | Some(Node::Directory(_)) => {
                if !args.is_empty() {
                    return Err(CliError::InvalidArgumentCount {
                        expected_min: 0,
                        expected_max: 0,
                        received: args.len(),
                    });
                }
                // Directory navigation - update path and return
                self.current_path = new_path;
                #[cfg(feature = "history")]
                return Ok(Response::success("")
                    .without_history()
                    .without_postfix_newline());
                #[cfg(not(feature = "history"))]
                return Ok(Response::success("").without_postfix_newline());
            }
            Some(Node::Command(cmd_meta)) => {
                // Case 2: Tree command execution
                // Check access control - use InvalidPath for security (don't reveal access denied)
                if let Some(user) = &self.current_user
                    && user.access_level < cmd_meta.access_level
                {
                    return Err(CliError::InvalidPath);
                }

                // Validate argument count
                if args.len() < cmd_meta.min_args || args.len() > cmd_meta.max_args {
                    return Err(CliError::InvalidArgumentCount {
                        expected_min: cmd_meta.min_args,
                        expected_max: cmd_meta.max_args,
                        received: args.len(),
                    });
                }

                // Dispatch to command handler (handle both sync and async)
                match cmd_meta.kind {
                    CommandKind::Sync => {
                        // Sync command in async context - call directly
                        self.handler.execute_sync(cmd_meta.id, args)
                    }
                    CommandKind::Async => {
                        // Async command - await execution
                        self.handler.execute_async(cmd_meta.id, args).await
                    }
                }
            }
        }
    }

    /// Resolve a path string to a node.
    ///
    /// Returns (node, path_stack) where path_stack is the navigation path.
    /// Node is None when path resolves to root directory.
    // TODO: Use C::MAX_PATH_DEPTH when const generics stabilize
    fn resolve_path(
        &self,
        path_str: &str,
    ) -> Result<(Option<&'tree Node<L>>, heapless::Vec<usize, 8>), CliError> {
        // Start from current directory or root
        // TODO: Use C::MAX_PATH_DEPTH when const generics stabilize
        let mut working_path: heapless::Vec<usize, 8> = if path_str.starts_with('/') {
            heapless::Vec::new() // Absolute path starts from root
        } else {
            self.current_path.clone() // Relative path starts from current
        };

        // Parse path
        // TODO: Use C::MAX_PATH_DEPTH when const generics stabilize
        let segments: heapless::Vec<&str, 8> = path_str
            .trim_start_matches('/')
            .split('/')
            .filter(|s| !s.is_empty() && *s != ".")
            .collect();

        // Navigate through segments
        for (seg_idx, segment) in segments.iter().enumerate() {
            if *segment == ".." {
                // Parent directory
                working_path.pop();
                continue;
            }

            let is_last_segment = seg_idx == segments.len() - 1;

            // Find child with this name
            let current_dir = self.get_dir_at_path(&working_path)?;
            let mut found = false;

            for (index, child) in current_dir.children.iter().enumerate() {
                // Check access control
                let node_level = match child {
                    Node::Command(cmd) => cmd.access_level,
                    Node::Directory(dir) => dir.access_level,
                };

                if let Some(user) = &self.current_user
                    && user.access_level < node_level
                {
                    continue; // User lacks access, skip this node
                }

                if child.name() == *segment {
                    // Found it!
                    if child.is_directory() {
                        // Navigate into directory
                        working_path
                            .push(index)
                            .map_err(|_| CliError::PathTooDeep)?;
                    } else {
                        // It's a command - can only return if this is the last segment
                        if is_last_segment {
                            return Ok((Some(child), working_path));
                        } else {
                            // Trying to navigate through a command - invalid path structure
                            return Err(CliError::InvalidPath);
                        }
                    }
                    found = true;
                    break;
                }
            }

            if !found {
                return Err(CliError::CommandNotFound);
            }
        }

        // Path resolved to a directory
        // Handle root directory specially (when path is empty)
        if working_path.is_empty() {
            // Return None to represent root directory
            return Ok((None, working_path));
        }

        let dir_node = self.get_node_at_path(&working_path)?;
        Ok((Some(dir_node), working_path))
    }

    /// Get directory at specific path.
    // TODO: Use C::MAX_PATH_DEPTH when const generics stabilize
    fn get_dir_at_path(
        &self,
        path: &heapless::Vec<usize, 8>,
    ) -> Result<&'tree Directory<L>, CliError> {
        let mut current: &Directory<L> = self.tree;

        for &index in path.iter() {
            match current.children.get(index) {
                Some(Node::Directory(dir)) => current = dir,
                Some(Node::Command(_)) | None => return Err(CliError::InvalidPath),
            }
        }

        Ok(current)
    }

    /// Get node at specific path.
    // TODO: Use C::MAX_PATH_DEPTH when const generics stabilize
    fn get_node_at_path(&self, path: &heapless::Vec<usize, 8>) -> Result<&'tree Node<L>, CliError> {
        if path.is_empty() {
            // Root directory - need to find a way to return it as a Node
            // For now, return error since we can't construct Node::Directory here
            return Err(CliError::InvalidPath);
        }

        // TODO: Use C::MAX_PATH_DEPTH when const generics stabilize
        let parent_path: heapless::Vec<usize, 8> =
            path.iter().take(path.len() - 1).copied().collect();
        let parent_dir = self.get_dir_at_path(&parent_path)?;

        let last_index = *path.last().ok_or(CliError::InvalidPath)?;
        parent_dir
            .children
            .get(last_index)
            .ok_or(CliError::InvalidPath)
    }

    /// Handle Tab completion.
    fn handle_tab(&mut self) -> Result<(), IO::Error> {
        #[cfg(feature = "completion")]
        {
            // Get current directory
            let current_dir = match self.get_current_dir() {
                Ok(dir) => dir,
                Err(_) => return self.generate_and_write_prompt(), // Error, just redraw prompt
            };

            // Suggest completions
            let result = suggest_completions::<L, 16>(
                current_dir,
                self.input_buffer.as_str(),
                self.current_user.as_ref(),
            );

            match result {
                Ok(crate::tree::completion::CompletionResult::Single { completion, .. }) => {
                    // Single match - replace buffer and update display
                    self.input_buffer.clear();
                    match self.input_buffer.push_str(&completion) {
                        Ok(()) => {
                            // Redraw line
                            self.io.write_str("\r")?; // Carriage return
                            let prompt = self.generate_prompt();
                            self.io.write_str(prompt.as_str())?;
                            self.io.write_str(self.input_buffer.as_str())?;
                        }
                        Err(_) => {
                            // Completion too long for buffer - beep
                            self.io.put_char('\x07')?;
                        }
                    }
                }
                Ok(crate::tree::completion::CompletionResult::Multiple { all_matches, .. }) => {
                    // Multiple matches - show them
                    self.io.write_str("\r\n")?;
                    for m in all_matches.iter() {
                        self.io.write_str("  ")?; // 2-space indentation
                        self.io.write_str(m.as_str())?;
                        self.io.write_str("  ")?;
                    }
                    self.io.write_str("\r\n")?;
                    self.generate_and_write_prompt()?;
                    self.io.write_str(self.input_buffer.as_str())?;
                }
                _ => {
                    // No matches or error - just beep
                    self.io.put_char('\x07')?; // Bell character
                }
            }
        }

        #[cfg(not(feature = "completion"))]
        {
            // Completion disabled - just beep
            self.io.put_char('\x07')?; // Bell character
        }

        Ok(())
    }

    /// Handle history navigation.
    fn handle_history(&mut self, direction: HistoryDirection) -> Result<(), IO::Error> {
        #[cfg(feature = "history")]
        {
            let history_entry = match direction {
                HistoryDirection::Previous => self.history.previous_command(),
                HistoryDirection::Next => self.history.next_command(),
            };

            if let Some(entry) = history_entry {
                // Replace buffer with history entry
                self.input_buffer = entry;
                // Redraw line
                self.clear_line_and_redraw()?;
            }
        }

        #[cfg(not(feature = "history"))]
        {
            // History disabled - ignore
            let _ = direction; // Silence unused warning
        }

        Ok(())
    }

    /// Show help (? command).
    fn show_help(&mut self) -> Result<(), IO::Error> {
        self.io.write_str("  ?        - List global commands\r\n")?;
        self.io
            .write_str("  ls       - List directory contents\r\n")?;

        #[cfg(feature = "authentication")]
        self.io.write_str("  logout   - End session\r\n")?;

        self.io.write_str("  clear    - Clear screen\r\n")?;
        self.io.write_str("  ESC ESC  - Clear input buffer\r\n")?;

        Ok(())
    }

    /// Show directory listing (ls command).
    fn show_ls(&mut self) -> Result<(), IO::Error> {
        let current_dir = match self.get_current_dir() {
            Ok(dir) => dir,
            Err(_) => {
                self.io.write_str("Error accessing directory\r\n")?;
                return Ok(());
            }
        };

        for child in current_dir.children.iter() {
            // Check access control
            let node_level = match child {
                Node::Command(cmd) => cmd.access_level,
                Node::Directory(dir) => dir.access_level,
            };

            if let Some(user) = &self.current_user
                && user.access_level < node_level
            {
                continue; // User lacks access, skip this node
            }

            // Format output
            match child {
                Node::Command(cmd) => {
                    self.io.write_str("  ")?;
                    self.io.write_str(cmd.name)?;
                    self.io.write_str("  - ")?;
                    self.io.write_str(cmd.description)?;
                    self.io.write_str("\r\n")?;
                }
                Node::Directory(dir) => {
                    self.io.write_str("  ")?;
                    self.io.write_str(dir.name)?;
                    self.io.write_str("/  - Directory\r\n")?;
                }
            }
        }

        Ok(())
    }

    /// Clear current line and redraw with prompt and buffer.
    fn clear_line_and_redraw(&mut self) -> Result<(), IO::Error> {
        self.io.write_str("\r\x1b[K")?; // CR + clear to end of line
        self.generate_and_write_prompt()?;
        self.io.write_str(self.input_buffer.as_str())?;
        Ok(())
    }

    // ========================================
    // I/O Access
    // ========================================

    /// Get reference to I/O interface (for inspection or direct control).
    pub fn io(&self) -> &IO {
        &self.io
    }

    /// Get mutable reference to I/O interface (for manipulation or direct control).
    pub fn io_mut(&mut self) -> &mut IO {
        &mut self.io
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::AccessLevel;
    use crate::config::DefaultConfig;
    use crate::io::CharIo;
    use crate::tree::{CommandKind, CommandMeta, Directory, Node};

    // Mock access level
    #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
    enum MockLevel {
        User = 0,
    }

    impl AccessLevel for MockLevel {
        fn from_str(s: &str) -> Option<Self> {
            match s {
                "User" => Some(Self::User),
                _ => None,
            }
        }

        fn as_str(&self) -> &'static str {
            "User"
        }
    }

    // Mock I/O that captures output
    struct MockIo {
        output: heapless::String<512>,
    }
    impl MockIo {
        fn new() -> Self {
            Self {
                output: heapless::String::new(),
            }
        }

        #[allow(dead_code)]
        fn get_output(&self) -> &str {
            &self.output
        }
    }
    impl CharIo for MockIo {
        type Error = ();
        fn get_char(&mut self) -> Result<Option<char>, ()> {
            Ok(None)
        }
        fn put_char(&mut self, c: char) -> Result<(), ()> {
            self.output.push(c).map_err(|_| ())
        }
        fn write_str(&mut self, s: &str) -> Result<(), ()> {
            self.output.push_str(s).map_err(|_| ())
        }
    }

    // Mock handler
    struct MockHandler;
    impl CommandHandler<DefaultConfig> for MockHandler {
        fn execute_sync(
            &self,
            _id: &str,
            _args: &[&str],
        ) -> Result<crate::response::Response<DefaultConfig>, crate::error::CliError> {
            Err(crate::error::CliError::CommandNotFound)
        }

        #[cfg(feature = "async")]
        async fn execute_async(
            &self,
            _id: &str,
            _args: &[&str],
        ) -> Result<crate::response::Response<DefaultConfig>, crate::error::CliError> {
            Err(crate::error::CliError::CommandNotFound)
        }
    }

    // Test commands
    const CMD_TEST: CommandMeta<MockLevel> = CommandMeta {
        id: "test-cmd",
        name: "test-cmd",
        description: "Test command",
        access_level: MockLevel::User,
        kind: CommandKind::Sync,
        min_args: 0,
        max_args: 0,
    };

    const CMD_REBOOT: CommandMeta<MockLevel> = CommandMeta {
        id: "reboot",
        name: "reboot",
        description: "Reboot the system",
        access_level: MockLevel::User,
        kind: CommandKind::Sync,
        min_args: 0,
        max_args: 0,
    };

    const CMD_STATUS: CommandMeta<MockLevel> = CommandMeta {
        id: "status",
        name: "status",
        description: "Show status",
        access_level: MockLevel::User,
        kind: CommandKind::Sync,
        min_args: 0,
        max_args: 0,
    };

    const CMD_LED: CommandMeta<MockLevel> = CommandMeta {
        id: "led",
        name: "led",
        description: "Control LED",
        access_level: MockLevel::User,
        kind: CommandKind::Sync,
        min_args: 1,
        max_args: 1,
    };

    const CMD_NETWORK_STATUS: CommandMeta<MockLevel> = CommandMeta {
        id: "network_status",
        name: "status",
        description: "Network status",
        access_level: MockLevel::User,
        kind: CommandKind::Sync,
        min_args: 0,
        max_args: 0,
    };

    // Test directories
    const DIR_HARDWARE: Directory<MockLevel> = Directory {
        name: "hardware",
        children: &[Node::Command(&CMD_LED)],
        access_level: MockLevel::User,
    };

    const DIR_NETWORK: Directory<MockLevel> = Directory {
        name: "network",
        children: &[Node::Command(&CMD_NETWORK_STATUS)],
        access_level: MockLevel::User,
    };

    const DIR_SYSTEM: Directory<MockLevel> = Directory {
        name: "system",
        children: &[
            Node::Command(&CMD_REBOOT),
            Node::Command(&CMD_STATUS),
            Node::Directory(&DIR_HARDWARE),
            Node::Directory(&DIR_NETWORK),
        ],
        access_level: MockLevel::User,
    };

    // Test tree
    const TEST_TREE: Directory<MockLevel> = Directory {
        name: "/",
        children: &[Node::Command(&CMD_TEST), Node::Directory(&DIR_SYSTEM)],
        access_level: MockLevel::User,
    };

    #[test]
    fn test_request_command_no_args() {
        let mut path = heapless::String::<128>::new();
        path.push_str("help").unwrap();
        let args = heapless::Vec::new();
        #[cfg(feature = "history")]
        let original = {
            let mut s = heapless::String::<128>::new();
            s.push_str("help").unwrap();
            s
        };

        let request = Request::<DefaultConfig>::Command {
            path,
            args,
            #[cfg(feature = "history")]
            original,
            _phantom: core::marker::PhantomData,
        };

        match request {
            Request::Command { path, args, .. } => {
                assert_eq!(path.as_str(), "help");
                assert_eq!(args.len(), 0);
            }
            #[allow(unreachable_patterns)]
            _ => panic!("Expected Command variant"),
        }
    }

    #[test]
    fn test_request_command_with_args() {
        let mut path = heapless::String::<128>::new();
        path.push_str("echo").unwrap();

        let mut args = heapless::Vec::new();
        let mut hello = heapless::String::<128>::new();
        hello.push_str("hello").unwrap();
        let mut world = heapless::String::<128>::new();
        world.push_str("world").unwrap();
        args.push(hello).unwrap();
        args.push(world).unwrap();

        #[cfg(feature = "history")]
        let original = {
            let mut s = heapless::String::<128>::new();
            s.push_str("echo hello world").unwrap();
            s
        };

        let request = Request::<DefaultConfig>::Command {
            path,
            args,
            #[cfg(feature = "history")]
            original,
            _phantom: core::marker::PhantomData,
        };

        match request {
            Request::Command { path, args, .. } => {
                assert_eq!(path.as_str(), "echo");
                assert_eq!(args.len(), 2);
                assert_eq!(args[0].as_str(), "hello");
                assert_eq!(args[1].as_str(), "world");
            }
            #[allow(unreachable_patterns)]
            _ => panic!("Expected Command variant"),
        }
    }

    #[test]
    #[cfg(feature = "history")]
    fn test_request_command_with_original() {
        let mut path = heapless::String::<128>::new();
        path.push_str("reboot").unwrap();
        let mut original = heapless::String::<128>::new();
        original.push_str("reboot").unwrap();

        let request = Request::<DefaultConfig>::Command {
            path,
            args: heapless::Vec::new(),
            original,
            _phantom: core::marker::PhantomData,
        };

        match request {
            Request::Command { path, original, .. } => {
                assert_eq!(path.as_str(), "reboot");
                assert_eq!(original.as_str(), "reboot");
            }
            #[allow(unreachable_patterns)]
            _ => panic!("Expected Command variant"),
        }
    }

    #[test]
    #[cfg(feature = "authentication")]
    fn test_request_login() {
        let mut username = heapless::String::<32>::new();
        username.push_str("admin").unwrap();
        let mut password = heapless::String::<64>::new();
        password.push_str("secret123").unwrap();

        let request = Request::<DefaultConfig>::Login { username, password };

        match request {
            Request::Login { username, password } => {
                assert_eq!(username.as_str(), "admin");
                assert_eq!(password.as_str(), "secret123");
            }
            #[allow(unreachable_patterns)]
            _ => panic!("Expected Login variant"),
        }
    }

    #[test]
    #[cfg(feature = "authentication")]
    fn test_request_invalid_login() {
        let request = Request::<DefaultConfig>::InvalidLogin;

        match request {
            Request::InvalidLogin => {}
            #[allow(unreachable_patterns)]
            _ => panic!("Expected InvalidLogin variant"),
        }
    }

    #[test]
    #[cfg(feature = "completion")]
    fn test_request_tab_complete() {
        let mut path = heapless::String::<128>::new();
        path.push_str("sys").unwrap();

        let request = Request::<DefaultConfig>::TabComplete { path };

        match request {
            Request::TabComplete { path } => {
                assert_eq!(path.as_str(), "sys");
            }
            #[allow(unreachable_patterns)]
            _ => panic!("Expected TabComplete variant"),
        }
    }

    #[test]
    #[cfg(feature = "completion")]
    fn test_request_tab_complete_empty() {
        let request = Request::<DefaultConfig>::TabComplete {
            path: heapless::String::new(),
        };

        match request {
            Request::TabComplete { path } => {
                assert_eq!(path.as_str(), "");
            }
            #[allow(unreachable_patterns)]
            _ => panic!("Expected TabComplete variant"),
        }
    }

    #[test]
    #[cfg(feature = "history")]
    fn test_request_history_previous() {
        let mut buffer = heapless::String::<128>::new();
        buffer.push_str("current input").unwrap();

        let request = Request::<DefaultConfig>::History {
            direction: HistoryDirection::Previous,
            buffer,
        };

        match request {
            Request::History { direction, buffer } => {
                assert_eq!(direction, HistoryDirection::Previous);
                assert_eq!(buffer.as_str(), "current input");
            }
            #[allow(unreachable_patterns)]
            _ => panic!("Expected History variant"),
        }
    }

    #[test]
    #[cfg(feature = "history")]
    fn test_request_history_next() {
        let request = Request::<DefaultConfig>::History {
            direction: HistoryDirection::Next,
            buffer: heapless::String::new(),
        };

        match request {
            Request::History { direction, buffer } => {
                assert_eq!(direction, HistoryDirection::Next);
                assert_eq!(buffer.as_str(), "");
            }
            #[allow(unreachable_patterns)]
            _ => panic!("Expected History variant"),
        }
    }

    #[test]
    fn test_request_variants_match_features() {
        let _cmd = Request::<DefaultConfig>::Command {
            path: heapless::String::new(),
            args: heapless::Vec::new(),
            #[cfg(feature = "history")]
            original: heapless::String::new(),
            _phantom: core::marker::PhantomData,
        };

        #[cfg(feature = "authentication")]
        let _login = Request::<DefaultConfig>::Login {
            username: heapless::String::new(),
            password: heapless::String::new(),
        };

        #[cfg(feature = "completion")]
        let _complete = Request::<DefaultConfig>::TabComplete {
            path: heapless::String::new(),
        };

        #[cfg(feature = "history")]
        let _history = Request::<DefaultConfig>::History {
            direction: HistoryDirection::Previous,
            buffer: heapless::String::new(),
        };
    }

    #[test]
    fn test_activate_deactivate_lifecycle() {
        let io = MockIo::new();
        let handler = MockHandler;

        // Create shell - should start in Inactive state
        #[cfg(feature = "authentication")]
        {
            use crate::auth::CredentialProvider;
            struct MockProvider;
            impl CredentialProvider<MockLevel> for MockProvider {
                type Error = ();
                fn find_user(
                    &self,
                    _username: &str,
                ) -> Result<Option<crate::auth::User<MockLevel>>, ()> {
                    Ok(None)
                }
                fn verify_password(
                    &self,
                    _user: &crate::auth::User<MockLevel>,
                    _password: &str,
                ) -> bool {
                    false
                }
            }
            let provider = MockProvider;
            let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
                Shell::new(&TEST_TREE, handler, &provider, io);

            // Should start in Inactive state
            assert_eq!(shell.state, CliState::Inactive);
            assert!(shell.current_user.is_none());

            // Activate should transition to LoggedOut (auth enabled)
            shell.activate().unwrap();
            assert_eq!(shell.state, CliState::LoggedOut);

            // Deactivate should return to Inactive
            shell.deactivate();
            assert_eq!(shell.state, CliState::Inactive);
            assert!(shell.current_user.is_none());
            assert!(shell.input_buffer.is_empty());
            assert!(shell.current_path.is_empty());
        }

        #[cfg(not(feature = "authentication"))]
        {
            let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
                Shell::new(&TEST_TREE, handler, io);

            // Should start in Inactive state
            assert_eq!(shell.state, CliState::Inactive);

            // Activate should transition to LoggedIn (auth disabled)
            shell.activate().unwrap();
            assert_eq!(shell.state, CliState::LoggedIn);

            // Deactivate should return to Inactive
            shell.deactivate();
            assert_eq!(shell.state, CliState::Inactive);
            assert!(shell.current_user.is_none());
            assert!(shell.input_buffer.is_empty());
            assert!(shell.current_path.is_empty());
        }
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_write_formatted_response_default() {
        // Test default formatting (no flags set)
        let io = MockIo::new();
        let handler = MockHandler;
        let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        let response = crate::response::Response::<DefaultConfig>::success("Test message");
        shell.write_formatted_response(&response).unwrap();

        // Default: message + postfix newline
        assert_eq!(shell.io.get_output(), "Test message\r\n");
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_write_formatted_response_with_prefix_newline() {
        let io = MockIo::new();
        let handler = MockHandler;
        let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        let response =
            crate::response::Response::<DefaultConfig>::success("Test").with_prefix_newline();
        shell.write_formatted_response(&response).unwrap();

        // prefix newline + message + postfix newline
        assert_eq!(shell.io.get_output(), "\r\nTest\r\n");
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_write_formatted_response_indented() {
        let io = MockIo::new();
        let handler = MockHandler;
        let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        let response =
            crate::response::Response::<DefaultConfig>::success("Line 1\r\nLine 2").indented();
        shell.write_formatted_response(&response).unwrap();

        // Each line indented with 2 spaces + postfix newline
        assert_eq!(shell.io.get_output(), "  Line 1\r\n  Line 2\r\n");
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_write_formatted_response_indented_single_line() {
        let io = MockIo::new();
        let handler = MockHandler;
        let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        let response =
            crate::response::Response::<DefaultConfig>::success("Single line").indented();
        shell.write_formatted_response(&response).unwrap();

        // Single line indented
        assert_eq!(shell.io.get_output(), "  Single line\r\n");
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_write_formatted_response_without_postfix_newline() {
        let io = MockIo::new();
        let handler = MockHandler;
        let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        let response = crate::response::Response::<DefaultConfig>::success("No newline")
            .without_postfix_newline();
        shell.write_formatted_response(&response).unwrap();

        // Message without trailing newline
        assert_eq!(shell.io.get_output(), "No newline");
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_write_formatted_response_combined_flags() {
        let io = MockIo::new();
        let handler = MockHandler;
        let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        let response = crate::response::Response::<DefaultConfig>::success("Multi\r\nLine")
            .with_prefix_newline()
            .indented();
        shell.write_formatted_response(&response).unwrap();

        // Prefix newline + indented lines + postfix newline
        assert_eq!(shell.io.get_output(), "\r\n  Multi\r\n  Line\r\n");
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_write_formatted_response_all_flags_off() {
        let io = MockIo::new();
        let handler = MockHandler;
        let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        let response =
            crate::response::Response::<DefaultConfig>::success("Raw").without_postfix_newline();
        shell.write_formatted_response(&response).unwrap();

        // No formatting at all
        assert_eq!(shell.io.get_output(), "Raw");
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_write_formatted_response_empty_message() {
        let io = MockIo::new();
        let handler = MockHandler;
        let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        let response = crate::response::Response::<DefaultConfig>::success("");
        shell.write_formatted_response(&response).unwrap();

        // Empty message still gets postfix newline
        assert_eq!(shell.io.get_output(), "\r\n");
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_write_formatted_response_indented_multiline() {
        let io = MockIo::new();
        let handler = MockHandler;
        let mut shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        let response = crate::response::Response::<DefaultConfig>::success("A\r\nB\r\nC\r\nD")
            .indented()
            .without_postfix_newline();
        shell.write_formatted_response(&response).unwrap();

        // All 4 lines indented, no trailing newline
        assert_eq!(shell.io.get_output(), "  A\r\n  B\r\n  C\r\n  D");
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_inline_message_flag() {
        // Test that inline_message flag is properly recognized
        let response =
            crate::response::Response::<DefaultConfig>::success("... processing").inline();

        assert!(
            response.inline_message,
            "inline() should set inline_message flag"
        );

        // Note: The actual inline behavior (no newline after input) is tested
        // via integration tests, as it requires simulating full command execution.
        // This test verifies the flag is set correctly.
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_resolve_path_cannot_navigate_through_command() {
        // Test that resolve_path returns InvalidPath when trying to navigate through a command
        let io = MockIo::new();
        let handler = MockHandler;
        let shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        // Valid: Command as last segment should succeed
        let result = shell.resolve_path("test-cmd");
        assert!(result.is_ok(), "Should resolve path to command");
        if let Ok((node, _)) = result {
            assert!(node.is_some());
            if let Some(Node::Command(cmd)) = node {
                assert_eq!(cmd.name, "test-cmd");
            } else {
                panic!("Expected Command node");
            }
        }

        // Invalid: Cannot navigate through command to another segment
        let result = shell.resolve_path("test-cmd/invalid");
        assert!(
            result.is_err(),
            "Should fail when navigating through command"
        );
        assert_eq!(
            result.unwrap_err(),
            CliError::InvalidPath,
            "Should return InvalidPath when trying to navigate through command"
        );

        // Invalid: Multiple segments after command
        let result = shell.resolve_path("test-cmd/extra/path");
        assert!(
            result.is_err(),
            "Should fail with multiple segments after command"
        );
        assert_eq!(
            result.unwrap_err(),
            CliError::InvalidPath,
            "Should return InvalidPath for multiple segments after command"
        );
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_resolve_path_comprehensive() {
        let io = MockIo::new();
        let handler = MockHandler;
        let shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        // Test 1: Root level command
        let result = shell.resolve_path("test-cmd");
        assert!(result.is_ok(), "Should resolve root-level command");
        if let Ok((node, _)) = result {
            assert!(node.is_some());
            if let Some(Node::Command(cmd)) = node {
                assert_eq!(cmd.name, "test-cmd");
            }
        }

        // Test 2: Verify command metadata properties
        let result = shell.resolve_path("system/reboot");
        assert!(result.is_ok(), "Should resolve system/reboot");
        if let Ok((node, _)) = result {
            assert!(node.is_some());
            if let Some(Node::Command(cmd)) = node {
                assert_eq!(cmd.name, "reboot");
                assert_eq!(cmd.description, "Reboot the system");
                assert_eq!(cmd.access_level, MockLevel::User);
                assert_eq!(cmd.kind, CommandKind::Sync);
            }
        }

        // Test 3: Verify unique command ID (critical for handler dispatch)
        let result = shell.resolve_path("system/status");
        assert!(result.is_ok(), "Should resolve system/status");
        if let Ok((node, _)) = result {
            assert!(node.is_some());
            if let Some(Node::Command(cmd)) = node {
                assert_eq!(cmd.name, "status");
                assert_eq!(cmd.id, "status");
                // Verify this is different from network/status which has id "network_status"
            }
        }

        // Test 4: Second-level nested command (system/network/status)
        let result = shell.resolve_path("system/network/status");
        assert!(result.is_ok(), "Should resolve system/network/status");
        if let Ok((node, _)) = result {
            assert!(node.is_some());
            if let Some(Node::Command(cmd)) = node {
                assert_eq!(cmd.name, "status");
            }
        }

        // Test 5: Second-level nested command (system/hardware/led)
        let result = shell.resolve_path("system/hardware/led");
        assert!(result.is_ok(), "Should resolve system/hardware/led");
        if let Ok((node, _)) = result {
            assert!(node.is_some());
            if let Some(Node::Command(cmd)) = node {
                assert_eq!(cmd.name, "led");
                assert_eq!(cmd.min_args, 1);
                assert_eq!(cmd.max_args, 1);
            }
        }

        // Test 6: Non-existent command at root
        let result = shell.resolve_path("nonexistent");
        assert!(result.is_err(), "Should fail for non-existent command");
        assert_eq!(
            result.unwrap_err(),
            CliError::CommandNotFound,
            "Should return CommandNotFound for non-existent command"
        );

        // Test 7: Invalid path (nonexistent directory)
        let result = shell.resolve_path("invalid/path/command");
        assert!(result.is_err(), "Should fail for nonexistent path");
        assert_eq!(
            result.unwrap_err(),
            CliError::CommandNotFound,
            "Should return CommandNotFound when first segment doesn't exist"
        );

        // Test 7b: Invalid path (attempting to navigate through a command)
        let result = shell.resolve_path("test-cmd/something");
        assert!(
            result.is_err(),
            "Should fail when navigating through command"
        );
        assert_eq!(
            result.unwrap_err(),
            CliError::InvalidPath,
            "Should return InvalidPath when trying to navigate through a command"
        );

        // Test 8: Resolve to directory (system)
        let result = shell.resolve_path("system");
        assert!(result.is_ok(), "Should resolve directory path");
        if let Ok((node, _)) = result {
            assert!(node.is_some());
            if let Some(Node::Directory(dir)) = node {
                assert_eq!(dir.name, "system");
            }
        }

        // Test 9: Resolve nested directory (system/network)
        let result = shell.resolve_path("system/network");
        assert!(result.is_ok(), "Should resolve nested directory");
        if let Ok((node, _)) = result {
            assert!(node.is_some());
            if let Some(Node::Directory(dir)) = node {
                assert_eq!(dir.name, "network");
            }
        }
    }

    #[test]
    #[cfg(not(feature = "authentication"))]
    fn test_resolve_path_parent_directory() {
        let io = MockIo::new();
        let handler = MockHandler;
        let shell: Shell<MockLevel, MockIo, MockHandler, DefaultConfig> =
            Shell::new(&TEST_TREE, handler, io);

        // Test 1: Navigate into directory then back up with ..
        // First navigate to system/network/status
        let result = shell.resolve_path("system/network/status");
        assert!(result.is_ok(), "Should resolve system/network/status");
        let (_, path) = result.unwrap();
        // Path should have indices for system (1), network (3)
        // [1] = system (index 1 in children of root: test-cmd, system)
        // [3] = network (index 3 in children of system: reboot, status, hardware, network)
        assert_eq!(
            path.len(),
            2,
            "Path should have 2 elements (system, network)"
        );
        assert_eq!(path[0], 1, "system should be at index 1 in root");
        assert_eq!(path[1], 3, "network should be at index 3 in system");

        // Test 2: Use .. to go back to system from system/network
        let result = shell.resolve_path("system/network/..");
        assert!(result.is_ok(), "Should resolve system/network/..");
        if let Ok((node, path)) = result {
            assert!(node.is_some());
            if let Some(Node::Directory(dir)) = node {
                assert_eq!(dir.name, "system", "Should be back at system directory");
            }
            assert_eq!(path.len(), 1, "Path should have 1 element");
            assert_eq!(path[0], 1, "system should be at index 1 in root");
        }

        // Test 3: Multiple .. to go back to root
        let result = shell.resolve_path("system/network/../..");
        assert!(result.is_ok(), "Should resolve system/network/../..");
        if let Ok((node, path)) = result {
            assert_eq!(path.len(), 0, "Path should be empty (at root)");
            assert!(node.is_none(), "Node should be None (representing root)");
        }

        // Test 4: Go beyond root with .. (should stay at root)
        let result = shell.resolve_path("..");
        assert!(result.is_ok(), "Should handle .. at root");
        if let Ok((node, path)) = result {
            assert_eq!(path.len(), 0, "Path should stay at root");
            assert!(node.is_none(), "Node should be None (representing root)");
        }
    }
}