click-rs 1.0.0

A Rust port of Python's Click library for creating command-line interfaces
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
//! Terminal UI utilities for click-rs.
//!
//! This module provides terminal input/output functions for building interactive
//! command-line applications. It includes styled output, user prompts, progress bars,
//! and terminal utilities.
//!
//! # Features
//!
//! - **Output Functions**: `echo`, `secho`, and `style` for formatted terminal output
//! - **Input Functions**: `prompt`, `confirm`, `getchar`, and `pause` for user input
//! - **Progress Bars**: Visual progress indication with ETA and percentage
//! - **Terminal Utilities**: Screen clearing, size detection, TTY checks
//!
//! # Example
//!
//! ```no_run
//! use click::termui::{echo, secho, style, prompt, confirm, Color};
//!
//! // Simple output
//! echo("Hello, world!", true, false, None);
//!
//! // Styled output
//! secho("Success!", Some(Color::Green), None, true, false, false, false, false, false, false, true, true, false, None);
//!
//! // Create a styled string
//! let styled = style("Error", Some(Color::Red), None, true, false, false, false, false, false, false, false);
//!
//! // Prompt for input
//! let name = prompt("Enter your name", Some("World".to_string()), false, false, |s| Ok(s.to_string())).unwrap();
//!
//! // Confirmation
//! if confirm("Continue?", Some(true), false).unwrap() {
//!     // proceed
//! }
//! ```

use std::io::{self, BufRead, Write};
use std::process::{Command as ProcessCommand, Stdio};
use std::time::Instant;

use crate::error::{ClickError, Result};

// ============================================================================
// Echo Macro
// ============================================================================

/// Convenience macro for printing to the terminal.
///
/// This macro wraps the `echo` function with a simpler syntax.
///
/// # Usage
///
/// ```no_run
/// use click::echo;
///
/// // Simple message with newline
/// echo!("Hello, world!");
///
/// // Without newline
/// echo!("Prompt: ", nl = false);
///
/// // To stderr
/// echo!("Error occurred", err = true);
///
/// // Combined
/// echo!("Warning: ", nl = false, err = true);
///
/// // With formatting
/// let name = "World";
/// echo!("Hello, {}!", name);
/// ```
#[macro_export]
macro_rules! echo {
    // Basic message
    ($msg:expr) => {
        $crate::termui::echo($msg, true, false, None)
    };
    // Message with format args
    ($fmt:expr, $($arg:tt)*) => {{
        // Check if first arg after format is a keyword arg
        echo!(@parse $fmt, $($arg)*)
    }};
    // Parse keyword arguments
    (@parse $fmt:expr, nl = $nl:expr) => {
        $crate::termui::echo($fmt, $nl, false, None)
    };
    (@parse $fmt:expr, err = $err:expr) => {
        $crate::termui::echo($fmt, true, $err, None)
    };
    (@parse $fmt:expr, nl = $nl:expr, err = $err:expr) => {
        $crate::termui::echo($fmt, $nl, $err, None)
    };
    (@parse $fmt:expr, err = $err:expr, nl = $nl:expr) => {
        $crate::termui::echo($fmt, $nl, $err, None)
    };
    (@parse $fmt:expr, color = $color:expr) => {
        $crate::termui::echo($fmt, true, false, $color)
    };
    (@parse $fmt:expr, nl = $nl:expr, color = $color:expr) => {
        $crate::termui::echo($fmt, $nl, false, $color)
    };
    (@parse $fmt:expr, err = $err:expr, color = $color:expr) => {
        $crate::termui::echo($fmt, true, $err, $color)
    };
    (@parse $fmt:expr, nl = $nl:expr, err = $err:expr, color = $color:expr) => {
        $crate::termui::echo($fmt, $nl, $err, $color)
    };
    // Format string with args (no keyword args)
    (@parse $fmt:expr, $($arg:tt)*) => {
        $crate::termui::echo(&format!($fmt, $($arg)*), true, false, None)
    };
}

// ============================================================================
// Color Constants
// ============================================================================

/// Terminal colors for styled output.
///
/// These colors correspond to standard ANSI terminal colors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Color {
    /// Black (ANSI code 30/40)
    Black,
    /// Red (ANSI code 31/41)
    Red,
    /// Green (ANSI code 32/42)
    Green,
    /// Yellow (ANSI code 33/43)
    Yellow,
    /// Blue (ANSI code 34/44)
    Blue,
    /// Magenta (ANSI code 35/45)
    Magenta,
    /// Cyan (ANSI code 36/46)
    Cyan,
    /// White (ANSI code 37/47)
    White,
    /// Bright Black (ANSI code 90/100)
    BrightBlack,
    /// Bright Red (ANSI code 91/101)
    BrightRed,
    /// Bright Green (ANSI code 92/102)
    BrightGreen,
    /// Bright Yellow (ANSI code 93/103)
    BrightYellow,
    /// Bright Blue (ANSI code 94/104)
    BrightBlue,
    /// Bright Magenta (ANSI code 95/105)
    BrightMagenta,
    /// Bright Cyan (ANSI code 96/106)
    BrightCyan,
    /// Bright White (ANSI code 97/107)
    BrightWhite,
    /// Reset color to default
    Reset,
}

impl Color {
    /// Get the ANSI foreground color code.
    pub fn fg_code(self) -> u8 {
        match self {
            Color::Black => 30,
            Color::Red => 31,
            Color::Green => 32,
            Color::Yellow => 33,
            Color::Blue => 34,
            Color::Magenta => 35,
            Color::Cyan => 36,
            Color::White => 37,
            Color::BrightBlack => 90,
            Color::BrightRed => 91,
            Color::BrightGreen => 92,
            Color::BrightYellow => 93,
            Color::BrightBlue => 94,
            Color::BrightMagenta => 95,
            Color::BrightCyan => 96,
            Color::BrightWhite => 97,
            Color::Reset => 39,
        }
    }

    /// Get the ANSI background color code.
    pub fn bg_code(self) -> u8 {
        match self {
            Color::Black => 40,
            Color::Red => 41,
            Color::Green => 42,
            Color::Yellow => 43,
            Color::Blue => 44,
            Color::Magenta => 45,
            Color::Cyan => 46,
            Color::White => 47,
            Color::BrightBlack => 100,
            Color::BrightRed => 101,
            Color::BrightGreen => 102,
            Color::BrightYellow => 103,
            Color::BrightBlue => 104,
            Color::BrightMagenta => 105,
            Color::BrightCyan => 106,
            Color::BrightWhite => 107,
            Color::Reset => 49,
        }
    }
}

// Color constants for convenience (Python Click compatibility)
pub const BLACK: Color = Color::Black;
pub const RED: Color = Color::Red;
pub const GREEN: Color = Color::Green;
pub const YELLOW: Color = Color::Yellow;
pub const BLUE: Color = Color::Blue;
pub const MAGENTA: Color = Color::Magenta;
pub const CYAN: Color = Color::Cyan;
pub const WHITE: Color = Color::White;
pub const BRIGHT_BLACK: Color = Color::BrightBlack;
pub const BRIGHT_RED: Color = Color::BrightRed;
pub const BRIGHT_GREEN: Color = Color::BrightGreen;
pub const BRIGHT_YELLOW: Color = Color::BrightYellow;
pub const BRIGHT_BLUE: Color = Color::BrightBlue;
pub const BRIGHT_MAGENTA: Color = Color::BrightMagenta;
pub const BRIGHT_CYAN: Color = Color::BrightCyan;
pub const BRIGHT_WHITE: Color = Color::BrightWhite;
pub const RESET: Color = Color::Reset;

// ============================================================================
// Terminal Detection
// ============================================================================

/// Check if a file descriptor refers to a TTY.
///
/// This checks if the given stream is connected to an interactive terminal.
///
/// # Arguments
///
/// * `stream` - The stream to check: "stdout", "stderr", or "stdin"
///
/// # Returns
///
/// `true` if the stream is a TTY, `false` otherwise.
///
/// # Note
///
/// This uses `std::io::IsTerminal` when available (MSRV: 1.70).
pub fn isatty(stream: &str) -> bool {
    use std::io::IsTerminal;
    match stream {
        "stdin" => std::io::stdin().is_terminal(),
        "stdout" => std::io::stdout().is_terminal(),
        "stderr" => std::io::stderr().is_terminal(),
        _ => false,
    }
}

/// Check if stdout is connected to a TTY.
pub fn stdout_isatty() -> bool {
    isatty("stdout")
}

/// Check if stderr is connected to a TTY.
pub fn stderr_isatty() -> bool {
    isatty("stderr")
}

/// Check if stdin is connected to a TTY.
pub fn stdin_isatty() -> bool {
    isatty("stdin")
}

/// Get the terminal size as (width, height).
///
/// Returns a default of (80, 24) if detection fails or if not connected to a TTY.
///
/// # Returns
///
/// A tuple of (width, height) in characters.
pub fn get_terminal_size() -> (usize, usize) {
    // Try environment variables first (portable)
    if let (Ok(cols), Ok(rows)) = (std::env::var("COLUMNS"), std::env::var("LINES")) {
        if let (Ok(w), Ok(h)) = (cols.parse::<usize>(), rows.parse::<usize>()) {
            if w > 0 && h > 0 {
                return (w, h);
            }
        }
    }

    // Use crossterm for OS-level detection (cross-platform, no unsafe)
    match crossterm::terminal::size() {
        Ok((cols, rows)) if cols > 0 && rows > 0 => (cols as usize, rows as usize),
        _ => (80, 24),
    }
}

/// Clear the terminal screen.
///
/// Uses ANSI escape sequences to clear the screen and move cursor to home.
/// On non-TTY outputs, this is a no-op.
pub fn clear() {
    if stdout_isatty() {
        // ANSI escape: clear screen and move to home
        print!("\x1b[2J\x1b[H");
        let _ = io::stdout().flush();
    }
}

// ============================================================================
// Styling Functions
// ============================================================================

/// Determine if ANSI codes should be used.
///
/// Returns true if:
/// - `color` is explicitly `Some(true)`
/// - `color` is `None` and the output stream is a TTY
fn should_use_color(color: Option<bool>, err: bool) -> bool {
    match color {
        Some(true) => true,
        Some(false) => false,
        None => {
            if err {
                stderr_isatty()
            } else {
                stdout_isatty()
            }
        }
    }
}

/// Style text with ANSI escape codes.
///
/// Creates a styled string with the specified formatting. If the terminal
/// doesn't support colors or formatting is disabled, returns the text unchanged.
///
/// # Arguments
///
/// * `text` - The text to style
/// * `fg` - Foreground color
/// * `bg` - Background color
/// * `bold` - Bold text
/// * `dim` - Dim (faint) text
/// * `underline` - Underlined text
/// * `overline` - Overlined text (not widely supported)
/// * `italic` - Italic text
/// * `blink` - Blinking text
/// * `strikethrough` - Strikethrough text
/// * `reset` - Whether to reset all styles at the end
///
/// # Returns
///
/// The styled string with ANSI escape codes.
#[allow(clippy::too_many_arguments)]
pub fn style(
    text: &str,
    fg: Option<Color>,
    bg: Option<Color>,
    bold: bool,
    dim: bool,
    underline: bool,
    overline: bool,
    italic: bool,
    blink: bool,
    strikethrough: bool,
    reset: bool,
) -> String {
    let mut codes = Vec::new();

    // Collect style codes
    if bold {
        codes.push("1".to_string());
    }
    if dim {
        codes.push("2".to_string());
    }
    if italic {
        codes.push("3".to_string());
    }
    if underline {
        codes.push("4".to_string());
    }
    if blink {
        codes.push("5".to_string());
    }
    if overline {
        codes.push("53".to_string()); // ANSI overline
    }
    if strikethrough {
        codes.push("9".to_string());
    }

    // Add colors
    if let Some(color) = fg {
        codes.push(color.fg_code().to_string());
    }
    if let Some(color) = bg {
        codes.push(color.bg_code().to_string());
    }

    if codes.is_empty() {
        return text.to_string();
    }

    let style_start = format!("\x1b[{}m", codes.join(";"));
    let style_end = if reset { "\x1b[0m" } else { "" };

    format!("{}{}{}", style_start, text, style_end)
}

/// Print a message to the terminal.
///
/// # Arguments
///
/// * `message` - The message to print
/// * `nl` - Whether to append a newline (default: true)
/// * `err` - Whether to print to stderr instead of stdout
/// * `color` - Force color on/off, or None to auto-detect
pub fn echo(message: &str, nl: bool, err: bool, color: Option<bool>) {
    let output = if should_use_color(color, err) {
        message.to_string()
    } else {
        // Strip ANSI codes if color is disabled
        strip_ansi_codes(message)
    };

    if err {
        if nl {
            eprintln!("{}", output);
            let _ = io::stderr().flush();
        } else {
            eprint!("{}", output);
            let _ = io::stderr().flush();
        }
    } else if nl {
        println!("{}", output);
        let _ = io::stdout().flush();
    } else {
        print!("{}", output);
        let _ = io::stdout().flush();
    }
}

/// Print a styled message to the terminal.
///
/// This is a convenience function that combines `style` and `echo`.
///
/// # Arguments
///
/// * `message` - The message to print
/// * `fg` - Foreground color
/// * `bg` - Background color
/// * `bold` - Bold text
/// * `dim` - Dim text
/// * `underline` - Underlined text
/// * `overline` - Overlined text
/// * `italic` - Italic text
/// * `blink` - Blinking text
/// * `strikethrough` - Strikethrough text
/// * `reset` - Whether to reset styles at end
/// * `nl` - Whether to append a newline
/// * `err` - Whether to print to stderr
/// * `color` - Force color on/off, or None to auto-detect
#[allow(clippy::too_many_arguments)]
pub fn secho(
    message: &str,
    fg: Option<Color>,
    bg: Option<Color>,
    bold: bool,
    dim: bool,
    underline: bool,
    overline: bool,
    italic: bool,
    blink: bool,
    strikethrough: bool,
    reset: bool,
    nl: bool,
    err: bool,
    color: Option<bool>,
) {
    let styled = if should_use_color(color, err) {
        style(
            message,
            fg,
            bg,
            bold,
            dim,
            underline,
            overline,
            italic,
            blink,
            strikethrough,
            reset,
        )
    } else {
        message.to_string()
    };

    if err {
        if nl {
            eprintln!("{}", styled);
        } else {
            eprint!("{}", styled);
            let _ = io::stderr().flush();
        }
    } else if nl {
        println!("{}", styled);
    } else {
        print!("{}", styled);
        let _ = io::stdout().flush();
    }
}

// ============================================================================
// Pager Support
// ============================================================================

/// Display text via a pager.
///
/// Pipes the given text to a pager program ($PAGER, less, or more).
/// Falls back to `echo()` if no pager is available or if not connected to a TTY.
///
/// # Arguments
///
/// * `text` - The text to display
/// * `color` - Whether to preserve ANSI color codes (None = auto-detect)
///
/// # Example
///
/// ```no_run
/// use click::termui::echo_via_pager;
///
/// let long_text = (0..100).map(|i| format!("Line {}", i)).collect::<Vec<_>>().join("\n");
/// echo_via_pager(&long_text, None);
/// ```
pub fn echo_via_pager(text: &str, color: Option<bool>) {
    // If not a TTY, just echo the text
    if !stdin_isatty() || !stdout_isatty() {
        echo(text, true, false, color);
        return;
    }

    // Determine the pager command
    let pager = std::env::var("PAGER")
        .ok()
        .filter(|p| !p.is_empty())
        .unwrap_or_else(|| {
            // Try to find less or more
            if which_pager("less").is_some() {
                "less".to_string()
            } else if which_pager("more").is_some() {
                "more".to_string()
            } else {
                String::new()
            }
        });

    if pager.is_empty() {
        // No pager available, fall back to echo
        echo(text, true, false, color);
        return;
    }

    // Prepare the text (strip ANSI codes if color is disabled)
    let output_text = if color == Some(false) {
        strip_ansi_codes(text)
    } else {
        text.to_string()
    };

    // Build the pager command with proper arguments
    let mut parts = pager.split_whitespace();
    let cmd_name = match parts.next() {
        Some(name) => name,
        None => {
            echo(&output_text, true, false, color);
            return;
        }
    };

    let mut cmd = ProcessCommand::new(cmd_name);

    // Add any additional arguments from $PAGER
    for arg in parts {
        cmd.arg(arg);
    }

    // If using less and color is enabled, add -R flag for raw control characters
    if cmd_name == "less" && color != Some(false) {
        cmd.arg("-R");
    }

    // Try to spawn the pager and pipe text to it
    match cmd.stdin(Stdio::piped()).spawn() {
        Ok(mut child) => {
            if let Some(mut stdin) = child.stdin.take() {
                let _ = stdin.write_all(output_text.as_bytes());
            }
            // Wait for pager to finish
            let _ = child.wait();
        }
        Err(_) => {
            // Pager failed to start, fall back to echo
            echo(&output_text, true, false, color);
        }
    }
}

/// Check if a pager command exists in PATH.
fn which_pager(name: &str) -> Option<String> {
    if let Ok(path) = std::env::var("PATH") {
        for dir in path.split(':') {
            let full_path = std::path::Path::new(dir).join(name);
            if full_path.exists() {
                return Some(full_path.to_string_lossy().into_owned());
            }
        }
    }
    None
}

// ============================================================================
// Launch Support
// ============================================================================

/// Open a URL or file path in the default application.
///
/// Uses platform-specific commands to launch the associated application:
/// - macOS: `open`
/// - Linux: `xdg-open`
/// - Windows: `start`
///
/// # Arguments
///
/// * `url` - The URL or file path to open
/// * `wait` - If true, wait for the application to finish before returning
/// * `locate` - If true, open a file manager showing the file location instead
///
/// # Returns
///
/// `Ok(())` on success, or an error if the launch failed.
///
/// # Example
///
/// ```no_run
/// use click::termui::launch;
///
/// # fn main() -> Result<(), click::ClickError> {
/// // Open a URL in the default browser
/// launch("https://example.com", false, false)?;
///
/// // Open a file in its default application
/// launch("/path/to/document.pdf", false, false)?;
///
/// // Show file location in file manager
/// launch("/path/to/file.txt", false, true)?;
/// # Ok(())
/// # }
/// ```
pub fn launch(url: &str, wait: bool, locate: bool) -> Result<()> {
    let (cmd, args) = get_launch_command(url, locate)?;

    let mut command = ProcessCommand::new(&cmd);
    command.args(&args);

    if wait {
        let status = command.status().map_err(|e| {
            ClickError::usage(format!("Failed to launch '{}': {}", url, e))
        })?;

        if !status.success() {
            return Err(ClickError::usage(format!(
                "Launch command failed with exit code: {:?}",
                status.code()
            )));
        }
    } else {
        // Spawn without waiting
        command.spawn().map_err(|e| {
            ClickError::usage(format!("Failed to launch '{}': {}", url, e))
        })?;
    }

    Ok(())
}

/// Get the platform-specific launch command and arguments.
fn get_launch_command(url: &str, locate: bool) -> Result<(String, Vec<String>)> {
    #[cfg(target_os = "macos")]
    {
        if locate {
            Ok(("open".to_string(), vec!["-R".to_string(), url.to_string()]))
        } else {
            Ok(("open".to_string(), vec![url.to_string()]))
        }
    }

    #[cfg(target_os = "linux")]
    {
        if locate {
            // Try to use a file manager that supports revealing files
            // First try dbus with nautilus/dolphin, fall back to xdg-open on parent dir
            let path = std::path::Path::new(url);
            if let Some(parent) = path.parent() {
                Ok((
                    "xdg-open".to_string(),
                    vec![parent.to_string_lossy().into_owned()],
                ))
            } else {
                Err(ClickError::usage(format!(
                    "Cannot locate file: {}",
                    url
                )))
            }
        } else {
            Ok(("xdg-open".to_string(), vec![url.to_string()]))
        }
    }

    #[cfg(target_os = "windows")]
    {
        if locate {
            // Use explorer with /select to highlight the file
            Ok((
                "explorer".to_string(),
                vec!["/select,".to_string() + url],
            ))
        } else {
            // Use cmd /c start for URLs and files
            Ok((
                "cmd".to_string(),
                vec!["/c".to_string(), "start".to_string(), "".to_string(), url.to_string()],
            ))
        }
    }

    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    {
        let _ = locate; // suppress unused warning
        Err(ClickError::usage(format!(
            "Platform not supported for launch: {}",
            url
        )))
    }
}

/// Strip ANSI escape codes from a string.
///
/// # Arguments
///
/// * `text` - The text to strip
///
/// # Returns
///
/// The text with all ANSI escape codes removed.
pub fn strip_ansi_codes(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // Skip the escape sequence
            if chars.peek() == Some(&'[') {
                chars.next(); // consume '['
                // Skip until we hit a letter (end of sequence)
                while let Some(&next) = chars.peek() {
                    chars.next();
                    if next.is_ascii_alphabetic() {
                        break;
                    }
                }
            }
        } else {
            result.push(c);
        }
    }

    result
}

// ============================================================================
// Input Functions
// ============================================================================

/// Prompt the user for input with optional type conversion.
///
/// # Arguments
///
/// * `text` - The prompt text to display
/// * `default` - Optional default value if user presses Enter
/// * `hide_input` - Whether to hide user input (for passwords)
/// * `confirmation` - Whether to prompt twice and require matching input
/// * `type_converter` - Function to convert and validate the input
///
/// # Returns
///
/// The converted user input, or an error.
///
/// # Notes
///
/// Hidden input requires terminal raw mode. If raw mode is unavailable,
/// input will be visible with a warning.
pub fn prompt<T, F>(
    text: &str,
    default: Option<T>,
    hide_input: bool,
    confirmation: bool,
    type_converter: F,
) -> Result<T>
where
    T: Clone + std::fmt::Display,
    F: Fn(&str) -> std::result::Result<T, String>,
{
    loop {
        // Build prompt string
        let prompt_text = if let Some(ref def) = default {
            format!("{} [{}]: ", text, def)
        } else {
            format!("{}: ", text)
        };

        // Read input
        let input = if hide_input {
            read_hidden_input(&prompt_text)?
        } else {
            read_line(&prompt_text)?
        };

        // Handle empty input with default
        let value = if input.is_empty() {
            if let Some(def) = default.clone() {
                return Ok(def);
            } else {
                echo("Error: This field is required.", true, true, None);
                continue;
            }
        } else {
            input
        };

        // Convert value
        let converted = match type_converter(&value) {
            Ok(v) => v,
            Err(msg) => {
                echo(&format!("Error: {}", msg), true, true, None);
                continue;
            }
        };

        // Handle confirmation
        if confirmation {
            let confirm_prompt = "Repeat for confirmation: ".to_string();
            let confirm_input = if hide_input {
                read_hidden_input(&confirm_prompt)?
            } else {
                read_line(&confirm_prompt)?
            };

            if confirm_input != value {
                echo(
                    "Error: The two entered values do not match.",
                    true,
                    true,
                    None,
                );
                continue;
            }
        }

        return Ok(converted);
    }
}

/// Prompt for yes/no confirmation.
///
/// # Arguments
///
/// * `text` - The prompt text to display
/// * `default` - Optional default value (true=yes, false=no)
/// * `abort` - Whether to raise Abort error on "no" answer
///
/// # Returns
///
/// `true` if user answered yes, `false` if no.
/// Returns `Err(ClickError::Abort)` if `abort` is true and user answered no.
pub fn confirm(text: &str, default: Option<bool>, abort: bool) -> Result<bool> {
    let suffix = match default {
        Some(true) => " [Y/n]: ",
        Some(false) => " [y/N]: ",
        None => " [y/n]: ",
    };

    loop {
        let prompt_text = format!("{}{}", text, suffix);
        let input = read_line(&prompt_text)?;
        let input_lower = input.to_lowercase();

        let result = if input.is_empty() {
            default
        } else if input_lower == "y" || input_lower == "yes" {
            Some(true)
        } else if input_lower == "n" || input_lower == "no" {
            Some(false)
        } else {
            echo("Error: invalid input", true, true, None);
            continue;
        };

        match result {
            Some(true) => return Ok(true),
            Some(false) => {
                if abort {
                    return Err(ClickError::Abort);
                }
                return Ok(false);
            }
            None => {
                echo("Error: invalid input", true, true, None);
                continue;
            }
        }
    }
}

/// Read a single character from the terminal.
///
/// # Arguments
///
/// * `echo_char` - Whether to echo the character back to the terminal
///
/// # Returns
///
/// The character read from the terminal.
///
/// # Notes
///
/// This function attempts to use raw mode for immediate character reading.
/// If raw mode is unavailable, it falls back to reading a line and returning
/// the first character.
pub fn getchar(echo_char: bool) -> Result<char> {
    use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
    use crossterm::terminal;

    if terminal::enable_raw_mode().is_ok() {
        let result = loop {
            match event::read() {
                Ok(Event::Key(KeyEvent {
                    code, modifiers, ..
                })) => {
                    if modifiers.contains(KeyModifiers::CONTROL) {
                        if let KeyCode::Char('c') = code {
                            break Err(ClickError::Abort);
                        }
                    }
                    match code {
                        KeyCode::Char(c) => break Ok(c),
                        KeyCode::Enter => break Ok('\n'),
                        KeyCode::Backspace => break Ok('\x7f'),
                        KeyCode::Tab => break Ok('\t'),
                        KeyCode::Esc => break Ok('\x1b'),
                        _ => continue,
                    }
                }
                Ok(_) => continue,
                Err(e) => {
                    break Err(ClickError::usage(format!("Failed to read key: {}", e)))
                }
            }
        };
        let _ = terminal::disable_raw_mode();

        if let Ok(c) = &result {
            if echo_char {
                print!("{}", c);
                let _ = io::stdout().flush();
            }
        }
        return result;
    }

    // Fallback: read a line and return the first character
    let input = read_line("")?;
    input.chars().next().ok_or(ClickError::Abort)
}

/// Pause until the user presses any key.
///
/// # Arguments
///
/// * `info` - Optional message to display (default: "Press any key to continue...")
pub fn pause(info: Option<&str>) {
    let message = info.unwrap_or("Press any key to continue...");
    echo(message, false, false, None);

    // Try to read a single character
    let _ = getchar(false);

    // Print newline
    println!();
}

/// Read a line of input from stdin.
fn read_line(prompt: &str) -> Result<String> {
    if !prompt.is_empty() {
        print!("{}", prompt);
        let _ = io::stdout().flush();
    }

    let stdin = io::stdin();
    let mut line = String::new();

    stdin
        .lock()
        .read_line(&mut line)
        .map_err(|e| ClickError::usage(format!("Failed to read input: {}", e)))?;

    // Trim the trailing newline
    if line.ends_with('\n') {
        line.pop();
        if line.ends_with('\r') {
            line.pop();
        }
    }

    Ok(line)
}

/// Read hidden input (for passwords).
///
/// Uses crossterm raw mode to read char-by-char without echo. Falls back to
/// visible input when not connected to a TTY (e.g., piped stdin in tests).
fn read_hidden_input(prompt: &str) -> Result<String> {
    use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
    use crossterm::terminal;

    if !prompt.is_empty() {
        print!("{}", prompt);
        let _ = io::stdout().flush();
    }

    // Try crossterm raw mode for hidden char-by-char reading (cross-platform, no unsafe).
    if terminal::enable_raw_mode().is_ok() {
        let mut input = String::new();
        let result = loop {
            match event::read() {
                Ok(Event::Key(KeyEvent {
                    code, modifiers, ..
                })) => {
                    if modifiers.contains(KeyModifiers::CONTROL) {
                        if let KeyCode::Char('c') = code {
                            break Err(ClickError::Abort);
                        }
                    }
                    match code {
                        KeyCode::Enter => break Ok(input.clone()),
                        KeyCode::Char(c) => input.push(c),
                        KeyCode::Backspace => {
                            input.pop();
                        }
                        _ => {}
                    }
                }
                Ok(_) => continue,
                Err(_) => break Ok(input.clone()),
            }
        };
        let _ = terminal::disable_raw_mode();
        println!();
        return result;
    }

    // Fallback: warn user and read normally (non-TTY, e.g., piped stdin)
    echo("(Warning: Input will be visible)", true, true, None);
    read_line("")
}

// ============================================================================
// Progress Bar
// ============================================================================

/// A progress bar for displaying operation progress.
///
/// # Example
///
/// ```no_run
/// use click::termui::ProgressBar;
///
/// let mut bar = ProgressBar::new(100, Some("Processing"), true, true, true, 40);
///
/// for i in 0..100 {
///     // Do work...
///     bar.update(1);
/// }
///
/// bar.finish();
///
/// // Custom fill/empty characters
/// let mut bar = ProgressBar::new(100, None, true, true, false, 30)
///     .fill_char('â–ˆ')
///     .empty_char('â–‘');
/// ```
pub struct ProgressBar {
    /// Total length of the progress (number of items)
    length: usize,
    /// Current position
    position: usize,
    /// Optional label to display
    label: Option<String>,
    /// Whether to show ETA
    show_eta: bool,
    /// Whether to show percentage
    show_percent: bool,
    /// Whether to show position/length
    show_pos: bool,
    /// Width of the progress bar in characters
    width: usize,
    /// Start time for ETA calculation
    start_time: Instant,
    /// Whether the bar is finished
    finished: bool,
    /// Whether output is a TTY
    is_tty: bool,
    /// Last rendered output length (for TTY updates)
    #[allow(dead_code)]
    last_output_len: usize,
    /// Character used for filled portion of bar (default: '#')
    fill_char: char,
    /// Character used for empty portion of bar (default: '-')
    empty_char: char,
}

impl ProgressBar {
    /// Create a new progress bar.
    ///
    /// # Arguments
    ///
    /// * `length` - Total number of items to process
    /// * `label` - Optional label to display before the bar
    /// * `show_eta` - Whether to show estimated time remaining
    /// * `show_percent` - Whether to show percentage complete
    /// * `show_pos` - Whether to show position/length
    /// * `width` - Width of the bar portion in characters
    pub fn new(
        length: usize,
        label: Option<&str>,
        show_eta: bool,
        show_percent: bool,
        show_pos: bool,
        width: usize,
    ) -> Self {
        let bar = Self {
            length,
            position: 0,
            label: label.map(String::from),
            show_eta,
            show_percent,
            show_pos,
            width,
            start_time: Instant::now(),
            finished: false,
            is_tty: stdout_isatty(),
            last_output_len: 0,
            fill_char: '#',
            empty_char: '-',
        };

        // Initial render
        bar.render_internal();
        bar
    }

    /// Set the character used for the filled portion of the bar.
    ///
    /// Default is '#'.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use click::termui::ProgressBar;
    /// let bar = ProgressBar::new(100, None, true, true, false, 30)
    ///     .fill_char('â–ˆ');
    /// ```
    pub fn fill_char(mut self, c: char) -> Self {
        self.fill_char = c;
        self
    }

    /// Set the character used for the empty portion of the bar.
    ///
    /// Default is '-'.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use click::termui::ProgressBar;
    /// let bar = ProgressBar::new(100, None, true, true, false, 30)
    ///     .empty_char('â–‘');
    /// ```
    pub fn empty_char(mut self, c: char) -> Self {
        self.empty_char = c;
        self
    }

    /// Update the progress bar by advancing by `n` items.
    ///
    /// # Arguments
    ///
    /// * `n` - Number of items completed since last update
    pub fn update(&mut self, n: usize) {
        if self.finished {
            return;
        }

        self.position = (self.position + n).min(self.length);
        self.render_internal();
    }

    /// Set the progress bar to a specific position.
    ///
    /// # Arguments
    ///
    /// * `pos` - New position
    pub fn set_position(&mut self, pos: usize) {
        if self.finished {
            return;
        }

        self.position = pos.min(self.length);
        self.render_internal();
    }

    /// Mark the progress bar as finished and render final state.
    pub fn finish(&mut self) {
        if self.finished {
            return;
        }

        self.position = self.length;
        self.finished = true;
        self.render_internal();

        // Print newline
        if self.is_tty {
            println!();
        }
    }

    /// Render the current progress bar state to a string.
    pub fn render(&self) -> String {
        let mut parts = Vec::new();

        // Label
        if let Some(ref label) = self.label {
            parts.push(label.clone());
        }

        // Calculate progress
        let progress = if self.length > 0 {
            self.position as f64 / self.length as f64
        } else {
            0.0
        };

        // Progress bar
        let filled = (progress * self.width as f64) as usize;
        let empty = self.width.saturating_sub(filled);
        let bar = format!(
            "[{}{}]",
            self.fill_char.to_string().repeat(filled),
            self.empty_char.to_string().repeat(empty)
        );
        parts.push(bar);

        // Percentage
        if self.show_percent {
            parts.push(format!("{:3.0}%", progress * 100.0));
        }

        // Position / Length
        if self.show_pos {
            parts.push(format!("{}/{}", self.position, self.length));
        }

        // ETA
        if self.show_eta && self.position > 0 && !self.finished {
            let elapsed = self.start_time.elapsed();
            let rate = self.position as f64 / elapsed.as_secs_f64();
            let remaining = self.length - self.position;
            let eta_secs = if rate > 0.0 {
                remaining as f64 / rate
            } else {
                0.0
            };

            if eta_secs < 3600.0 {
                let mins = (eta_secs / 60.0) as u64;
                let secs = (eta_secs % 60.0) as u64;
                parts.push(format!("eta {:02}:{:02}", mins, secs));
            } else {
                let hours = (eta_secs / 3600.0) as u64;
                let mins = ((eta_secs % 3600.0) / 60.0) as u64;
                parts.push(format!("eta {}h {:02}m", hours, mins));
            }
        }

        parts.join(" ")
    }

    /// Internal render method that updates the terminal.
    fn render_internal(&self) {
        let output = self.render();

        if self.is_tty {
            // Carriage return to beginning of line
            print!("\r{}", output);
            // Clear any remaining characters from previous output
            let clear_len = self.last_output_len.saturating_sub(output.len());
            if clear_len > 0 {
                print!("{}", " ".repeat(clear_len));
                print!("\r{}", output);
            }
            let _ = io::stdout().flush();
        } else {
            // Non-TTY: print on new lines
            println!("{}", output);
        }
    }
}

impl Drop for ProgressBar {
    fn drop(&mut self) {
        if !self.finished && self.is_tty {
            // Ensure we leave the terminal in a clean state
            println!();
        }
    }
}

/// Wrap an iterator with a progress bar display.
///
/// # Arguments
///
/// * `iter` - The iterator to wrap
/// * `length` - Total length (for percentage/ETA), or None to infer from iterator
/// * `label` - Optional label to display
///
/// # Returns
///
/// An iterator that displays progress as items are consumed.
///
/// # Example
///
/// ```no_run
/// use click::termui::progressbar;
///
/// let items = vec![1, 2, 3, 4, 5];
/// for item in progressbar(items.iter(), Some(items.len()), Some("Processing")) {
///     // Process item
/// }
/// ```
pub fn progressbar<I>(
    iter: I,
    length: Option<usize>,
    label: Option<&str>,
) -> ProgressBarIter<I::IntoIter>
where
    I: IntoIterator,
    I::IntoIter: ExactSizeIterator,
{
    let iter = iter.into_iter();
    let len = length.unwrap_or_else(|| iter.len());

    ProgressBarIter {
        iter,
        bar: ProgressBar::new(len, label, true, true, true, 30),
    }
}

/// An iterator wrapper that displays a progress bar.
pub struct ProgressBarIter<I> {
    iter: I,
    bar: ProgressBar,
}

impl<I> Iterator for ProgressBarIter<I>
where
    I: Iterator,
{
    type Item = I::Item;

    fn next(&mut self) -> Option<Self::Item> {
        match self.iter.next() {
            Some(item) => {
                self.bar.update(1);
                Some(item)
            }
            None => {
                self.bar.finish();
                None
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<I: ExactSizeIterator> ExactSizeIterator for ProgressBarIter<I> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

// ============================================================================
// Editor Support
// ============================================================================

/// Open a text editor for the user to edit content.
///
/// # Arguments
///
/// * `text` - Initial text to populate the editor with
/// * `editor` - Editor command to use, or None to use $EDITOR/$VISUAL/vi
/// * `extension` - File extension for the temporary file
/// * `require_save` - If true, return None if user didn't save
///
/// # Returns
///
/// The edited text, or None if editing was cancelled.
pub fn edit_text(
    text: Option<&str>,
    editor: Option<&str>,
    extension: &str,
    require_save: bool,
) -> Result<Option<String>> {
    use std::fs;
    use std::process::Command;

    // Create temporary file
    let temp_dir = std::env::temp_dir();
    let temp_file = temp_dir.join(format!("click_edit_{}.{}", std::process::id(), extension));

    // Write initial content
    if let Some(initial) = text {
        fs::write(&temp_file, initial)
            .map_err(|e| ClickError::file_error(&temp_file, e.to_string()))?;
    }

    // Get modification time before editing
    let mtime_before = fs::metadata(&temp_file)
        .ok()
        .and_then(|m| m.modified().ok());

    // Determine editor
    let editor_cmd = editor
        .map(String::from)
        .or_else(|| std::env::var("VISUAL").ok())
        .or_else(|| std::env::var("EDITOR").ok())
        .unwrap_or_else(|| "vi".to_string());

    // Run editor
    let status = Command::new(&editor_cmd)
        .arg(&temp_file)
        .status()
        .map_err(|e| ClickError::usage(format!("Failed to run editor '{}': {}", editor_cmd, e)))?;

    if !status.success() {
        let _ = fs::remove_file(&temp_file);
        return Err(ClickError::usage(format!(
            "Editor '{}' exited with error",
            editor_cmd
        )));
    }

    // Check if file was modified
    if require_save {
        let mtime_after = fs::metadata(&temp_file)
            .ok()
            .and_then(|m| m.modified().ok());

        if mtime_before == mtime_after {
            let _ = fs::remove_file(&temp_file);
            return Ok(None);
        }
    }

    // Read edited content
    let content = fs::read_to_string(&temp_file)
        .map_err(|e| ClickError::file_error(&temp_file, e.to_string()))?;

    // Clean up
    let _ = fs::remove_file(&temp_file);

    Ok(Some(content))
}

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

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

    #[test]
    fn test_color_codes() {
        assert_eq!(Color::Red.fg_code(), 31);
        assert_eq!(Color::Red.bg_code(), 41);
        assert_eq!(Color::BrightGreen.fg_code(), 92);
        assert_eq!(Color::BrightGreen.bg_code(), 102);
        assert_eq!(Color::Reset.fg_code(), 39);
        assert_eq!(Color::Reset.bg_code(), 49);
    }

    #[test]
    fn test_style_basic() {
        let styled = style(
            "hello", None, None, false, false, false, false, false, false, false, false,
        );
        assert_eq!(styled, "hello");
    }

    #[test]
    fn test_style_with_color() {
        let styled = style(
            "hello",
            Some(Color::Red),
            None,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            true,
        );
        assert_eq!(styled, "\x1b[31mhello\x1b[0m");
    }

    #[test]
    fn test_style_bold() {
        let styled = style(
            "hello", None, None, true, false, false, false, false, false, false, true,
        );
        assert_eq!(styled, "\x1b[1mhello\x1b[0m");
    }

    #[test]
    fn test_style_multiple() {
        let styled = style(
            "hello",
            Some(Color::Green),
            Some(Color::Black),
            true,
            false,
            true,
            false,
            false,
            false,
            false,
            true,
        );
        // Should have: bold (1), underline (4), fg green (32), bg black (40)
        assert!(styled.starts_with("\x1b["));
        assert!(styled.contains("1"));
        assert!(styled.contains("4"));
        assert!(styled.contains("32"));
        assert!(styled.contains("40"));
        assert!(styled.ends_with("\x1b[0m"));
    }

    #[test]
    fn test_strip_ansi_codes() {
        let styled = "\x1b[31mhello\x1b[0m world";
        let stripped = strip_ansi_codes(styled);
        assert_eq!(stripped, "hello world");

        let plain = "no codes here";
        assert_eq!(strip_ansi_codes(plain), "no codes here");
    }

    #[test]
    fn test_strip_ansi_codes_complex() {
        let styled = "\x1b[1;31;40mcomplex\x1b[0m";
        let stripped = strip_ansi_codes(styled);
        assert_eq!(stripped, "complex");
    }

    #[test]
    fn test_get_terminal_size_returns_valid() {
        let (width, height) = get_terminal_size();
        assert!(width > 0);
        assert!(height > 0);
    }

    #[test]
    fn test_progress_bar_render() {
        let bar = ProgressBar::new(100, Some("Test"), false, true, true, 20);
        let output = bar.render();
        assert!(output.contains("Test"));
        assert!(output.contains("["));
        assert!(output.contains("]"));
        assert!(output.contains("0/100"));
        assert!(output.contains("0%"));
    }

    #[test]
    fn test_progress_bar_update() {
        let mut bar = ProgressBar::new(100, None, false, true, false, 10);
        bar.update(50);
        let output = bar.render();
        assert!(output.contains("50%"));
    }

    #[test]
    fn test_progress_bar_finish() {
        let mut bar = ProgressBar::new(100, None, false, true, false, 10);
        bar.finish();
        let output = bar.render();
        assert!(output.contains("100%"));
        assert!(bar.finished);
    }

    #[test]
    fn test_progress_bar_zero_length() {
        let bar = ProgressBar::new(0, None, false, true, false, 10);
        let output = bar.render();
        assert!(output.contains("0%"));
    }

    #[test]
    fn test_progress_bar_custom_chars() {
        let mut bar = ProgressBar::new(100, None, false, false, false, 10)
            .fill_char('=')
            .empty_char(' ');
        bar.set_position(50);
        let output = bar.render();
        // Should have 5 '=' chars and 5 ' ' chars (50% of width 10)
        assert!(output.contains("[=====     ]"));
    }

    #[test]
    fn test_progress_bar_unicode_chars() {
        let bar = ProgressBar::new(100, None, false, false, false, 4)
            .fill_char('\u{2588}')  // Full block
            .empty_char('\u{2591}'); // Light shade
        let output = bar.render();
        // At 0%, should be all empty chars
        assert!(output.contains("[\u{2591}\u{2591}\u{2591}\u{2591}]"));
    }

    #[test]
    fn test_color_constants() {
        assert_eq!(BLACK, Color::Black);
        assert_eq!(RED, Color::Red);
        assert_eq!(GREEN, Color::Green);
        assert_eq!(YELLOW, Color::Yellow);
        assert_eq!(BLUE, Color::Blue);
        assert_eq!(MAGENTA, Color::Magenta);
        assert_eq!(CYAN, Color::Cyan);
        assert_eq!(WHITE, Color::White);
        assert_eq!(BRIGHT_BLACK, Color::BrightBlack);
        assert_eq!(BRIGHT_RED, Color::BrightRed);
        assert_eq!(BRIGHT_GREEN, Color::BrightGreen);
        assert_eq!(BRIGHT_YELLOW, Color::BrightYellow);
        assert_eq!(BRIGHT_BLUE, Color::BrightBlue);
        assert_eq!(BRIGHT_MAGENTA, Color::BrightMagenta);
        assert_eq!(BRIGHT_CYAN, Color::BrightCyan);
        assert_eq!(BRIGHT_WHITE, Color::BrightWhite);
        assert_eq!(RESET, Color::Reset);
    }

    #[test]
    fn test_style_all_options() {
        let styled = style(
            "test",
            Some(Color::Blue),
            Some(Color::White),
            true,  // bold
            true,  // dim
            true,  // underline
            true,  // overline
            true,  // italic
            true,  // blink
            true,  // strikethrough
            true,  // reset
        );
        assert!(styled.starts_with("\x1b["));
        assert!(styled.contains("1")); // bold
        assert!(styled.contains("2")); // dim
        assert!(styled.contains("3")); // italic
        assert!(styled.contains("4")); // underline
        assert!(styled.contains("5")); // blink
        assert!(styled.contains("9")); // strikethrough
        assert!(styled.contains("53")); // overline
        assert!(styled.contains("34")); // blue fg
        assert!(styled.contains("47")); // white bg
        assert!(styled.ends_with("\x1b[0m"));
    }

    #[test]
    fn test_style_no_reset() {
        let styled = style(
            "hello",
            Some(Color::Red),
            None,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
            false,
        );
        assert!(styled.starts_with("\x1b[31m"));
        assert!(!styled.ends_with("\x1b[0m"));
    }
}