winx-code-agent 0.2.315

High-performance Rust implementation of WCGW for LLM code agents
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
//! ANSI terminal code definitions and handlers
//!
//! This module provides constants and utilities for handling ANSI escape codes
//! commonly used in terminal output, focusing on rich text formatting including
//! 24-bit true color and extended attribute support.

use regex::Regex;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::OnceLock;

static ANSI_REGEX: OnceLock<std::result::Result<Regex, regex::Error>> = OnceLock::new();
const BASIC_COLORS: &[(&str, u8)] = &[
    ("black", 0),
    ("red", 1),
    ("green", 2),
    ("yellow", 3),
    ("blue", 4),
    ("magenta", 5),
    ("cyan", 6),
    ("white", 7),
    ("brightblack", 8),
    ("brightred", 9),
    ("brightgreen", 10),
    ("brightyellow", 11),
    ("brightblue", 12),
    ("brightmagenta", 13),
    ("brightcyan", 14),
    ("brightwhite", 15),
];

fn ansi_regex() -> Option<&'static Regex> {
    ANSI_REGEX.get_or_init(|| Regex::new(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")).as_ref().ok()
}

/// Basic ANSI control codes
pub mod control {
    /// Bell
    pub const BEL: &str = "\x07";
    /// Backspace
    pub const BS: &str = "\x08";
    /// Horizontal tab
    pub const HT: &str = "\x09";
    /// Line feed
    pub const LF: &str = "\x0A";
    /// Vertical tab
    pub const VT: &str = "\x0B";
    /// Form feed
    pub const FF: &str = "\x0C";
    /// Carriage return
    pub const CR: &str = "\x0D";
    /// Escape
    pub const ESC: &str = "\x1B";
    /// Delete
    pub const DEL: &str = "\x7F";
}

/// CSI (Control Sequence Introducer) sequences
pub mod csi {
    /// CSI sequence start
    pub const CSI: &str = "\x1B[";

    /// Cursor Up
    pub fn cursor_up(n: usize) -> String {
        format!("\x1B[{n}A")
    }

    /// Cursor Down
    pub fn cursor_down(n: usize) -> String {
        format!("\x1B[{n}B")
    }

    /// Cursor Forward
    pub fn cursor_forward(n: usize) -> String {
        format!("\x1B[{n}C")
    }

    /// Cursor Back
    pub fn cursor_back(n: usize) -> String {
        format!("\x1B[{n}D")
    }

    /// Cursor Next Line
    pub fn cursor_next_line(n: usize) -> String {
        format!("\x1B[{n}E")
    }

    /// Cursor Previous Line
    pub fn cursor_prev_line(n: usize) -> String {
        format!("\x1B[{n}F")
    }

    /// Cursor Horizontal Absolute
    pub fn cursor_horizontal(n: usize) -> String {
        format!("\x1B[{n}G")
    }

    /// Cursor Position (row, column)
    pub fn cursor_position(row: usize, col: usize) -> String {
        format!("\x1B[{row};{col}H")
    }

    /// Erase in Display
    pub fn erase_in_display(n: usize) -> String {
        format!("\x1B[{n}J")
    }

    /// Erase in Line
    pub fn erase_in_line(n: usize) -> String {
        format!("\x1B[{n}K")
    }

    /// Scroll Up
    pub fn scroll_up(n: usize) -> String {
        format!("\x1B[{n}S")
    }

    /// Scroll Down
    pub fn scroll_down(n: usize) -> String {
        format!("\x1B[{n}T")
    }

    /// Request Cursor Position
    pub const REQUEST_CURSOR_POSITION: &str = "\x1B[6n";

    /// Save Cursor Position
    pub const SAVE_CURSOR_POSITION: &str = "\x1B[s";

    /// Restore Cursor Position
    pub const RESTORE_CURSOR_POSITION: &str = "\x1B[u";

    /// Hide Cursor
    pub const HIDE_CURSOR: &str = "\x1B[?25l";

    /// Show Cursor
    pub const SHOW_CURSOR: &str = "\x1B[?25h";

    /// Enable Alternative Screen Buffer
    pub const ENABLE_ALT_SCREEN: &str = "\x1B[?1049h";

    /// Disable Alternative Screen Buffer
    pub const DISABLE_ALT_SCREEN: &str = "\x1B[?1049l";
}

/// SGR (Select Graphic Rendition) for text styling
pub mod sgr {
    /// Reset all attributes
    pub const RESET: &str = "\x1B[0m";

    /// Bold
    pub const BOLD: &str = "\x1B[1m";

    /// Faint/Dim
    pub const DIM: &str = "\x1B[2m";

    /// Italic
    pub const ITALIC: &str = "\x1B[3m";

    /// Underline
    pub const UNDERLINE: &str = "\x1B[4m";

    /// Slow Blink
    pub const BLINK: &str = "\x1B[5m";

    /// Rapid Blink
    pub const RAPID_BLINK: &str = "\x1B[6m";

    /// Reverse Video
    pub const REVERSE: &str = "\x1B[7m";

    /// Conceal/Hide
    pub const CONCEAL: &str = "\x1B[8m";

    /// Crossed-out/Strike
    pub const STRIKE: &str = "\x1B[9m";

    /// Primary/Default Font
    pub const PRIMARY_FONT: &str = "\x1B[10m";

    /// Alternative Font 1-9
    pub fn alt_font(n: usize) -> String {
        if !(1..=9).contains(&n) {
            return String::new();
        }
        format!("\x1B[{}m", 10 + n)
    }

    /// Fraktur (Gothic)
    pub const FRAKTUR: &str = "\x1B[20m";

    /// Double Underline
    pub const DOUBLE_UNDERLINE: &str = "\x1B[21m";

    /// Normal Intensity (not bold and not faint)
    pub const NORMAL_INTENSITY: &str = "\x1B[22m";

    /// Not Italic, Not Fraktur
    pub const NO_ITALIC: &str = "\x1B[23m";

    /// Not Underlined
    pub const NO_UNDERLINE: &str = "\x1B[24m";

    /// Not Blinking
    pub const NO_BLINK: &str = "\x1B[25m";

    /// Proportional Spacing
    pub const PROPORTIONAL_SPACING: &str = "\x1B[26m";

    /// Not Reversed
    pub const NO_REVERSE: &str = "\x1B[27m";

    /// Reveal (Not Concealed)
    pub const REVEAL: &str = "\x1B[28m";

    /// Not Crossed Out
    pub const NO_STRIKE: &str = "\x1B[29m";

    /// Foreground Color (30-37 for basic colors, 90-97 for bright)
    pub fn fg_color(n: usize) -> String {
        format!("\x1B[{n}m")
    }

    /// Background Color (40-47 for basic colors, 100-107 for bright)
    pub fn bg_color(n: usize) -> String {
        format!("\x1B[{n}m")
    }

    /// 8-bit Foreground Color (0-255)
    pub fn fg_color_256(n: u8) -> String {
        format!("\x1B[38;5;{n}m")
    }

    /// 8-bit Background Color (0-255)
    pub fn bg_color_256(n: u8) -> String {
        format!("\x1B[48;5;{n}m")
    }

    /// 24-bit Foreground Color (RGB)
    pub fn fg_color_rgb(r: u8, g: u8, b: u8) -> String {
        format!("\x1B[38;2;{r};{g};{b}m")
    }

    /// 24-bit Background Color (RGB)
    pub fn bg_color_rgb(r: u8, g: u8, b: u8) -> String {
        format!("\x1B[48;2;{r};{g};{b}m")
    }

    /// Default Foreground Color
    pub const DEFAULT_FG: &str = "\x1B[39m";

    /// Default Background Color
    pub const DEFAULT_BG: &str = "\x1B[49m";

    /// Disable Proportional Spacing
    pub const NO_PROPORTIONAL_SPACING: &str = "\x1B[50m";

    /// Framed
    pub const FRAMED: &str = "\x1B[51m";

    /// Encircled
    pub const ENCIRCLED: &str = "\x1B[52m";

    /// Overlined
    pub const OVERLINED: &str = "\x1B[53m";

    /// Not Framed, Not Encircled
    pub const NO_FRAMED: &str = "\x1B[54m";

    /// Not Overlined
    pub const NO_OVERLINED: &str = "\x1B[55m";

    /// Ideogram Underline
    pub const IDEOGRAM_UNDERLINE: &str = "\x1B[60m";

    /// Ideogram Double Underline
    pub const IDEOGRAM_DOUBLE_UNDERLINE: &str = "\x1B[61m";

    /// Ideogram Overline
    pub const IDEOGRAM_OVERLINE: &str = "\x1B[62m";

    /// Ideogram Double Overline
    pub const IDEOGRAM_DOUBLE_OVERLINE: &str = "\x1B[63m";

    /// Ideogram Stress Marking
    pub const IDEOGRAM_STRESS: &str = "\x1B[64m";

    /// No Ideogram Attributes
    pub const NO_IDEOGRAM: &str = "\x1B[65m";

    /// Superscript
    pub const SUPERSCRIPT: &str = "\x1B[73m";

    /// Subscript
    pub const SUBSCRIPT: &str = "\x1B[74m";

    /// Neither Superscript nor Subscript
    pub const NO_SCRIPT: &str = "\x1B[75m";
}

/// OSC (Operating System Command) sequences
pub mod osc {
    /// Set window title
    pub fn set_title(title: &str) -> String {
        format!("\x1B]0;{title}\x07")
    }

    /// Set window and icon title
    pub fn set_window_icon_title(title: &str) -> String {
        format!("\x1B]2;{title}\x07")
    }

    /// Set icon title
    pub fn set_icon_title(title: &str) -> String {
        format!("\x1B]1;{title}\x07")
    }

    /// Set color definition
    pub fn set_color(num: u8, rgb: &str) -> String {
        format!("\x1B]4;{num};{rgb}\x07")
    }

    /// Hyperlink
    pub fn hyperlink(url: &str, text: &str) -> String {
        format!("\x1B]8;;{url}\x07{text}\x1B]8;;\x07")
    }
}

/// Mouse reporting modes
pub mod mouse {
    /// Enable normal mouse tracking
    pub const NORMAL_TRACKING: &str = "\x1B[?1000h";

    /// Disable normal mouse tracking
    pub const NO_NORMAL_TRACKING: &str = "\x1B[?1000l";

    /// Enable highlight mouse tracking
    pub const HIGHLIGHT_TRACKING: &str = "\x1B[?1001h";

    /// Disable highlight mouse tracking
    pub const NO_HIGHLIGHT_TRACKING: &str = "\x1B[?1001l";

    /// Enable button-event tracking
    pub const BUTTON_EVENT_TRACKING: &str = "\x1B[?1002h";

    /// Disable button-event tracking
    pub const NO_BUTTON_EVENT_TRACKING: &str = "\x1B[?1002l";

    /// Enable any-event tracking
    pub const ANY_EVENT_TRACKING: &str = "\x1B[?1003h";

    /// Disable any-event tracking
    pub const NO_ANY_EVENT_TRACKING: &str = "\x1B[?1003l";

    /// Enable focus tracking
    pub const FOCUS_TRACKING: &str = "\x1B[?1004h";

    /// Disable focus tracking
    pub const NO_FOCUS_TRACKING: &str = "\x1B[?1004l";

    /// Enable extended mouse coordinates
    pub const EXTENDED_COORDINATES: &str = "\x1B[?1006h";

    /// Disable extended mouse coordinates
    pub const NO_EXTENDED_COORDINATES: &str = "\x1B[?1006l";

    /// Enable SGR mouse coordinates
    pub const SGR_COORDINATES: &str = "\x1B[?1016h";

    /// Disable SGR mouse coordinates
    pub const NO_SGR_COORDINATES: &str = "\x1B[?1016l";
}

/// Mode switching sequences
pub mod modes {
    /// Application Cursor Keys (DECCKM)
    pub const APPLICATION_CURSOR_KEYS: &str = "\x1B[?1h";

    /// Normal Cursor Keys
    pub const NORMAL_CURSOR_KEYS: &str = "\x1B[?1l";

    /// ANSI Mode (vs VT52)
    pub const ANSI_MODE: &str = "\x1B[?2h";

    /// VT52 Mode
    pub const VT52_MODE: &str = "\x1B[?2l";

    /// 132 Column Mode (DECCOLM)
    pub const MODE_132_COLUMN: &str = "\x1B[?3h";

    /// 80 Column Mode
    pub const MODE_80_COLUMN: &str = "\x1B[?3l";

    /// Smooth Scroll (DECSCLM)
    pub const SMOOTH_SCROLL: &str = "\x1B[?4h";

    /// Jump Scroll
    pub const JUMP_SCROLL: &str = "\x1B[?4l";

    /// Reverse Screen (DECSCNM)
    pub const REVERSE_SCREEN: &str = "\x1B[?5h";

    /// Normal Screen
    pub const NORMAL_SCREEN: &str = "\x1B[?5l";

    /// Application Keypad (DECNKM)
    pub const APPLICATION_KEYPAD: &str = "\x1B[?66h";

    /// Numeric Keypad
    pub const NUMERIC_KEYPAD: &str = "\x1B[?66l";

    /// Wraparound Mode (DECAWM)
    pub const WRAPAROUND: &str = "\x1B[?7h";

    /// No Wraparound
    pub const NO_WRAPAROUND: &str = "\x1B[?7l";

    /// Auto-repeat Keys (DECARM)
    pub const AUTOREPEAT_KEYS: &str = "\x1B[?8h";

    /// No Auto-repeat Keys
    pub const NO_AUTOREPEAT_KEYS: &str = "\x1B[?8l";

    /// Send Mouse X & Y on button press
    pub const MOUSE_TRACKING: &str = "\x1B[?9h";

    /// No Mouse Tracking
    pub const NO_MOUSE_TRACKING: &str = "\x1B[?9l";

    /// Show toolbar (rxvt)
    pub const SHOW_TOOLBAR: &str = "\x1B[?10h";

    /// Hide toolbar
    pub const HIDE_TOOLBAR: &str = "\x1B[?10l";

    /// Start Blinking Cursor
    pub const BLINKING_CURSOR: &str = "\x1B[?12h";

    /// Stop Blinking Cursor
    pub const NO_BLINKING_CURSOR: &str = "\x1B[?12l";

    /// Print Form Feed (DECPFF)
    pub const PRINT_FORM_FEED: &str = "\x1B[?18h";

    /// No Form Feed
    pub const NO_PRINT_FORM_FEED: &str = "\x1B[?18l";

    /// Set Print Screen (DECPEX)
    pub const PRINT_SCREEN: &str = "\x1B[?19h";

    /// No Print Screen
    pub const NO_PRINT_SCREEN: &str = "\x1B[?19l";

    /// Enable Linefeed/Newline Mode (LNM)
    pub const NEWLINE_MODE: &str = "\x1B[20h";

    /// Disable Linefeed/Newline Mode
    pub const NO_NEWLINE_MODE: &str = "\x1B[20l";
}

/// Terminal color code definitions
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TermColor {
    /// Standard basic color (0-15)
    Basic(u8),

    /// 256-color mode (0-255)
    Color256(u8),

    /// 24-bit RGB color
    TrueColor {
        /// Red component (0-255)
        r: u8,
        /// Green component (0-255)
        g: u8,
        /// Blue component (0-255)
        b: u8,
    },
}

impl TermColor {
    /// Get the ANSI code for foreground color
    pub fn fg_code(&self) -> String {
        match self {
            TermColor::Basic(n) if *n < 8 => format!("\x1B[{}m", 30 + n),
            TermColor::Basic(n) if *n < 16 => format!("\x1B[{}m", 82 + n),
            TermColor::Basic(n) | TermColor::Color256(n) => sgr::fg_color_256(*n),
            TermColor::TrueColor { r, g, b } => sgr::fg_color_rgb(*r, *g, *b),
        }
    }

    /// Get the ANSI code for background color
    pub fn bg_code(&self) -> String {
        match self {
            TermColor::Basic(n) if *n < 8 => format!("\x1B[{}m", 40 + n),
            TermColor::Basic(n) if *n < 16 => format!("\x1B[{}m", 92 + n),
            TermColor::Basic(n) | TermColor::Color256(n) => sgr::bg_color_256(*n),
            TermColor::TrueColor { r, g, b } => sgr::bg_color_rgb(*r, *g, *b),
        }
    }
}

/// Parse ANSI escape sequences in text
///
/// This extracts all escape sequences based on their type and position
///
/// # Arguments
///
/// * `text` - The text containing ANSI escape sequences
///
/// # Returns
///
/// A vector of (position, sequence) tuples
pub fn parse_ansi_sequences(text: &str) -> Vec<(usize, String)> {
    ansi_regex().map_or_else(Vec::new, |regex| {
        regex.find_iter(text).map(|m| (m.start(), m.as_str().to_string())).collect()
    })
}

/// Color name to ANSI code mapping
pub fn color_name_to_code(name: &str) -> Option<TermColor> {
    // Try as a basic color name
    if let Some((_, code)) = BASIC_COLORS.iter().find(|(color, _)| color.eq_ignore_ascii_case(name))
    {
        return Some(TermColor::Basic(*code));
    }

    // Try as a color number first (before hex parsing)
    if let Ok(num) = u8::from_str(name) {
        return Some(TermColor::Color256(num));
    }

    // Try as a hex color (only if it starts with # or is clearly hex)
    if name.starts_with('#') || (name.len() == 6 && name.chars().all(|c| c.is_ascii_hexdigit())) {
        if let Some(color) = parse_hex_color(name) {
            return Some(color);
        }
    }

    None
}

/// Parse a hex color into `TermColor`
///
/// Supports formats like #RGB, #RRGGBB
fn parse_hex_color(hex: &str) -> Option<TermColor> {
    let hex = hex.trim_start_matches('#');

    match hex.len() {
        3 => {
            // #RGB format
            let r = u8::from_str_radix(&hex[0..1], 16).ok()?;
            let g = u8::from_str_radix(&hex[1..2], 16).ok()?;
            let b = u8::from_str_radix(&hex[2..3], 16).ok()?;

            // Convert from 0-15 to 0-255 range
            let r = r * 17;
            let g = g * 17;
            let b = b * 17;

            Some(TermColor::TrueColor { r, g, b })
        }
        6 => {
            // #RRGGBB format
            let r = u8::from_str_radix(&hex[0..2], 16).ok()?;
            let g = u8::from_str_radix(&hex[2..4], 16).ok()?;
            let b = u8::from_str_radix(&hex[4..6], 16).ok()?;

            Some(TermColor::TrueColor { r, g, b })
        }
        _ => None,
    }
}

/// Format text with ANSI styling
///
/// This is a convenience function to easily add common ANSI styles
///
/// # Arguments
///
/// * `text` - The text to format
/// * `bold` - Whether to make the text bold
/// * `italic` - Whether to make the text italic
/// * `underline` - Whether to underline the text
/// * `fg_color` - Optional foreground color
/// * `bg_color` - Optional background color
///
/// # Returns
///
/// The formatted text with ANSI codes
pub fn format_ansi_text(
    text: &str,
    bold: bool,
    italic: bool,
    underline: bool,
    fg_color: Option<&TermColor>,
    bg_color: Option<&TermColor>,
) -> String {
    let mut result = String::new();

    // Add style codes
    if bold {
        result.push_str(sgr::BOLD);
    }
    if italic {
        result.push_str(sgr::ITALIC);
    }
    if underline {
        result.push_str(sgr::UNDERLINE);
    }

    // Add color codes
    if let Some(color) = fg_color {
        result.push_str(&color.fg_code());
    }
    if let Some(color) = bg_color {
        result.push_str(&color.bg_code());
    }

    // Add text and reset
    result.push_str(text);
    result.push_str(sgr::RESET);

    result
}

/// Strip all ANSI escape sequences from text
///
/// # Arguments
///
/// * `text` - The text containing ANSI escape sequences
///
/// # Returns
///
/// The text with all ANSI sequences removed
pub fn strip_ansi_codes(text: &str) -> String {
    ansi_regex().map_or_else(|| text.to_string(), |regex| regex.replace_all(text, "").to_string())
}

/// Extract structured style information from ANSI-formatted text
///
/// # Arguments
///
/// * `text` - The text with ANSI escape sequences
///
/// # Returns
///
/// A vector of (position, styles) where styles is a map of active styles
pub fn extract_ansi_styles(text: &str) -> Vec<(usize, HashMap<String, String>)> {
    let mut result = Vec::new();
    let mut current_styles = HashMap::new();
    let mut pos = 0;

    for (idx, seq) in parse_ansi_sequences(text) {
        // Adjust position for any actual text content
        if idx > pos {
            result.push((pos, current_styles.clone()));
            // No need to update pos here as it's updated below
        }

        // Process the sequence and update styles
        if seq == sgr::RESET {
            current_styles.clear();
        } else if seq == sgr::BOLD {
            current_styles.insert("weight".to_string(), "bold".to_string());
        } else if seq == sgr::ITALIC {
            current_styles.insert("style".to_string(), "italic".to_string());
        } else if seq == sgr::UNDERLINE {
            current_styles.insert("text-decoration".to_string(), "underline".to_string());
        } else if seq.starts_with("\x1B[38;") {
            current_styles.insert("color".to_string(), extract_color_from_seq(&seq));
        } else if seq.starts_with("\x1B[48;") {
            current_styles.insert("background-color".to_string(), extract_color_from_seq(&seq));
        }

        // Move position past the sequence
        pos = idx + seq.len();
    }

    // Add final segment if needed
    if pos < text.len() {
        result.push((pos, current_styles));
    }

    result
}

/// Extract color information from an SGR color sequence
fn extract_color_from_seq(seq: &str) -> String {
    if seq.starts_with("\x1B[38;5;") || seq.starts_with("\x1B[48;5;") {
        // 8-bit color
        let parts: Vec<&str> = seq.split(';').collect();
        if parts.len() >= 3 {
            if let Some(color_part) = parts[2].strip_suffix('m') {
                return format!("color-{color_part}");
            }
        }
    } else if seq.starts_with("\x1B[38;2;") || seq.starts_with("\x1B[48;2;") {
        // 24-bit color
        let parts: Vec<&str> = seq.split(';').collect();
        if parts.len() >= 5 {
            let r = parts[2];
            let g = parts[3];
            let b =
                if let Some(stripped) = parts[4].strip_suffix('m') { stripped } else { parts[4] };
            return format!("rgb({r},{g},{b})");
        }
    }

    "unknown".to_string()
}

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

    #[test]
    fn test_term_color() {
        let red = TermColor::Basic(1);
        assert_eq!(red.fg_code(), "\x1B[31m");
        assert_eq!(red.bg_code(), "\x1B[41m");

        let color256 = TermColor::Color256(128);
        assert_eq!(color256.fg_code(), "\x1B[38;5;128m");
        assert_eq!(color256.bg_code(), "\x1B[48;5;128m");

        let true_color = TermColor::TrueColor { r: 255, g: 128, b: 64 };
        assert_eq!(true_color.fg_code(), "\x1B[38;2;255;128;64m");
        assert_eq!(true_color.bg_code(), "\x1B[48;2;255;128;64m");
    }

    #[test]
    fn test_color_name_to_code() {
        assert_eq!(color_name_to_code("red"), Some(TermColor::Basic(1)));
        assert_eq!(color_name_to_code("brightblue"), Some(TermColor::Basic(12)));
        assert_eq!(color_name_to_code("123"), Some(TermColor::Color256(123)));

        assert_eq!(
            color_name_to_code("#ff00ff"),
            Some(TermColor::TrueColor { r: 255, g: 0, b: 255 })
        );

        assert_eq!(color_name_to_code("#f0f"), Some(TermColor::TrueColor { r: 255, g: 0, b: 255 }));
    }

    #[test]
    fn test_format_ansi_text() {
        let text = format_ansi_text("Hello", true, false, true, Some(&TermColor::Basic(1)), None);
        assert_eq!(text, "\x1B[1m\x1B[4m\x1B[31mHello\x1B[0m");
    }

    #[test]
    fn test_strip_ansi_codes() {
        let input = "\x1B[1m\x1B[31mHello\x1B[0m \x1B[32mWorld\x1B[0m";
        let output = strip_ansi_codes(input);
        assert_eq!(output, "Hello World");
    }

    #[test]
    fn test_parse_ansi_sequences() {
        let input = "Normal \x1B[1mBold\x1B[0m Normal";
        let sequences = parse_ansi_sequences(input);
        assert_eq!(sequences.len(), 2);
        assert_eq!(sequences[0], (7, "\x1B[1m".to_string()));
        assert_eq!(sequences[1], (15, "\x1B[0m".to_string()));
    }
}