seqlings 3.0.7

Interactive exercises for learning Seq, a stack-based programming language
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
//! Seqlings - Interactive exercises for learning Seq
//!
//! A rustlings-inspired tool for learning stack-based programming with Seq.

mod exercise;
mod runner;

use clap::{Parser, Subcommand};
use colored::Colorize;
use exercise::{Exercise, ExerciseStatus, load_exercises};
use include_dir::{include_dir, Dir};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process;
use std::time::{Duration, SystemTime};

// Embed exercise files at compile time
static EXERCISES_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/exercises");
static SOLUTIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/solutions");
static HINTS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/hints");

/// Cache for exercise status to avoid repeated compiler invocations
struct StatusCache {
    /// Maps exercise path to (last_mtime, cached_status)
    cache: HashMap<PathBuf, (SystemTime, ExerciseStatus)>,
}

impl StatusCache {
    fn new() -> Self {
        Self {
            cache: HashMap::new(),
        }
    }

    /// Get the status of an exercise, using cache when possible.
    /// This is the main optimization: we only re-run the compiler
    /// when the file has actually changed.
    fn get_status(&mut self, exercise: &Exercise) -> ExerciseStatus {
        // Get current file mtime
        let current_mtime = match std::fs::metadata(&exercise.path) {
            Ok(meta) => meta.modified().ok(),
            Err(_) => return ExerciseStatus::CompileError,
        };

        // Quick pre-filter: if file contains "# I AM NOT DONE", skip expensive checks
        // This is a cheap read that can short-circuit compiler invocation
        if let Ok(content) = std::fs::read_to_string(&exercise.path)
            && content.contains("# I AM NOT DONE") {
                // Update cache with NotDone status
                if let Some(mtime) = current_mtime {
                    self.cache.insert(exercise.path.clone(), (mtime, ExerciseStatus::NotDone));
                }
                return ExerciseStatus::NotDone;
            }

        // Check cache: if mtime unchanged, return cached status
        if let Some(mtime) = current_mtime
            && let Some((cached_mtime, cached_status)) = self.cache.get(&exercise.path)
                && *cached_mtime == mtime {
                    return cached_status.clone();
                }

        // Cache miss or file changed - run the full status check
        let status = exercise.status();

        // Update cache
        if let Some(mtime) = current_mtime {
            self.cache.insert(exercise.path.clone(), (mtime, status.clone()));
        }

        status
    }

    /// Clear the cache (useful for commands that need fresh data)
    #[allow(dead_code)]
    fn clear(&mut self) {
        self.cache.clear();
    }
}

#[derive(Parser)]
#[command(name = "seqlings")]
#[command(version, about = "Interactive exercises for learning Seq")]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize a new seqlings project directory
    Init {
        /// Directory name (defaults to "my-seqlings")
        #[arg(default_value = "my-seqlings")]
        path: PathBuf,
    },
    /// Watch for file changes and auto-verify exercises
    Watch {
        /// Filter to a specific chapter (e.g., "07" or "07-conditionals")
        #[arg(short, long)]
        chapter: Option<String>,
    },
    /// List all exercises with their status
    List {
        /// Filter to a specific chapter (e.g., "07" or "07-conditionals")
        #[arg(short, long)]
        chapter: Option<String>,
    },
    /// Show hint for the current or specified exercise
    Hint {
        /// Exercise name (optional, defaults to current)
        name: Option<String>,
    },
    /// Reset an exercise to its original state
    Reset {
        /// Exercise name (optional, defaults to current)
        name: Option<String>,
    },
    /// Verify all exercises and show progress
    Verify,
    /// Skip to the next exercise
    Next,
}

fn main() {
    let cli = Cli::parse();

    // Handle init command before loading exercises (since exercises may not exist yet)
    if let Some(Commands::Init { path }) = cli.command {
        cmd_init(&path);
        return;
    }

    // Load exercises
    let exercises = match load_exercises() {
        Ok(ex) => ex,
        Err(e) => {
            eprintln!("{} {}", "Error loading exercises:".red(), e);
            eprintln!("\n{}", "Hint: Run 'seqlings init' to create a new project.".yellow());
            process::exit(1);
        }
    };

    if exercises.is_empty() {
        eprintln!("{}", "No exercises found in exercises/info.toml".red());
        eprintln!("\n{}", "Hint: Run 'seqlings init' to create a new project.".yellow());
        process::exit(1);
    }

    match cli.command {
        Some(Commands::Init { .. }) => unreachable!(), // Handled above
        Some(Commands::Watch { chapter }) => {
            let filtered = filter_by_chapter(&exercises, chapter.as_deref());
            cmd_watch(&filtered);
        }
        Some(Commands::List { chapter }) => {
            let filtered = filter_by_chapter(&exercises, chapter.as_deref());
            cmd_list(&filtered);
        }
        Some(Commands::Hint { name }) => cmd_hint(&exercises, name),
        Some(Commands::Reset { name }) => cmd_reset(&exercises, name),
        Some(Commands::Verify) => cmd_verify(&exercises),
        Some(Commands::Next) => cmd_next(&exercises),
        None => cmd_watch(&exercises), // Default to watch mode
    }
}

/// Filter exercises to a specific chapter by prefix match
fn filter_by_chapter(exercises: &[Exercise], chapter: Option<&str>) -> Vec<Exercise> {
    match chapter {
        None => exercises.to_vec(),
        Some(prefix) => {
            let filtered: Vec<Exercise> = exercises
                .iter()
                .filter(|e| {
                    // Extract chapter directory name from path (e.g., "07-conditionals")
                    let chapter_name = e.path
                        .parent()
                        .and_then(|p| p.file_name())
                        .and_then(|s| s.to_str())
                        .unwrap_or("");
                    // Match if chapter name starts with the prefix
                    chapter_name.starts_with(prefix)
                })
                .cloned()
                .collect();

            if filtered.is_empty() {
                eprintln!(
                    "{} No exercises found for chapter '{}'",
                    "Warning:".yellow(),
                    prefix
                );
                eprintln!("Available chapters:");
                // Show unique chapter names
                let mut chapters: Vec<&str> = exercises
                    .iter()
                    .filter_map(|e| {
                        e.path
                            .parent()
                            .and_then(|p| p.file_name())
                            .and_then(|s| s.to_str())
                    })
                    .collect();
                chapters.sort();
                chapters.dedup();
                for ch in chapters {
                    eprintln!("  {}", ch);
                }
                process::exit(1);
            }

            println!(
                "{} Filtering to chapter '{}' ({} exercises)\n",
                "Note:".cyan(),
                prefix,
                filtered.len()
            );
            filtered
        }
    }
}

/// Initialize a new seqlings project directory
fn cmd_init(path: &Path) {
    // Check if directory already exists
    if path.exists() {
        eprintln!(
            "{} Directory '{}' already exists.",
            "Error:".red(),
            path.display()
        );
        eprintln!("Choose a different name or remove the existing directory.");
        process::exit(1);
    }

    println!(
        "{} Initializing seqlings project in '{}'...",
        "".cyan(),
        path.display()
    );

    // Create the main directory
    if let Err(e) = std::fs::create_dir_all(path) {
        eprintln!("{} Failed to create directory: {}", "Error:".red(), e);
        process::exit(1);
    }

    // Extract exercises
    let exercises_path = path.join("exercises");
    if let Err(e) = extract_dir(&EXERCISES_DIR, &exercises_path) {
        eprintln!("{} Failed to extract exercises: {}", "Error:".red(), e);
        process::exit(1);
    }
    println!("  {} exercises/", "".green());

    // Extract solutions
    let solutions_path = path.join("solutions");
    if let Err(e) = extract_dir(&SOLUTIONS_DIR, &solutions_path) {
        eprintln!("{} Failed to extract solutions: {}", "Error:".red(), e);
        process::exit(1);
    }
    println!("  {} solutions/", "".green());

    // Extract hints
    let hints_path = path.join("hints");
    if let Err(e) = extract_dir(&HINTS_DIR, &hints_path) {
        eprintln!("{} Failed to extract hints: {}", "Error:".red(), e);
        process::exit(1);
    }
    println!("  {} hints/", "".green());

    println!(
        "\n{} Project initialized successfully!",
        "".green().bold()
    );
    println!("\nTo get started:");
    println!("  {} {}", "cd".cyan(), path.display());
    println!("  {}", "seqlings".cyan());
}

/// Extract an embedded directory to the filesystem
fn extract_dir(dir: &Dir, target: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(target)?;

    for entry in dir.entries() {
        let entry_path = target.join(entry.path().file_name().unwrap_or_default());

        match entry {
            include_dir::DirEntry::Dir(subdir) => {
                extract_dir(subdir, &entry_path)?;
            }
            include_dir::DirEntry::File(file) => {
                if let Some(parent) = entry_path.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                std::fs::write(&entry_path, file.contents())?;
            }
        }
    }

    Ok(())
}

/// Watch mode: continuously monitor exercises and provide feedback
fn cmd_watch(exercises: &[Exercise]) {
    println!(
        "\n{}",
        "Welcome to seqlings watch mode!".green().bold()
    );
    println!("{}", "Edit exercises in your editor. Progress updates automatically.".dimmed());
    println!("{}", "Press Ctrl+C to exit.\n".dimmed());

    // Create status cache to avoid repeated compiler invocations
    let mut cache = StatusCache::new();

    // Warm up cache with progress indicator
    print!("{}", "Checking exercises...".dimmed());
    use std::io::Write;
    std::io::stdout().flush().ok();

    for (i, ex) in exercises.iter().enumerate() {
        cache.get_status(ex);
        // Show progress dot every 5 exercises
        if (i + 1) % 5 == 0 {
            print!(".");
            std::io::stdout().flush().ok();
        }
    }
    println!(" {}", "done".green());

    // Initial display
    let mut current_exercise_name = String::new();
    display_current_exercise(exercises, &mut current_exercise_name, &mut cache);

    loop {
        std::thread::sleep(Duration::from_millis(250));

        // Check files every 250ms
        let mut changed = false;
        for ex in exercises {
            if let Ok(meta) = std::fs::metadata(&ex.path)
                && let Ok(mtime) = meta.modified()
                    && mtime.elapsed().unwrap_or(Duration::from_secs(1000)) < Duration::from_millis(500) {
                        changed = true;
                        break;
                    }
        }

        if changed {
            clear_screen();
            display_current_exercise(exercises, &mut current_exercise_name, &mut cache);
        }
    }
}

fn clear_screen() {
    // ANSI escape to clear screen and move cursor to top
    print!("\x1B[2J\x1B[1;1H");
    use std::io::Write;
    std::io::stdout().flush().ok();
}

fn display_current_exercise(exercises: &[Exercise], previous_name: &mut String, cache: &mut StatusCache) {
    // Find first incomplete exercise using cached status
    let current = exercises.iter().find(|e| {
        matches!(
            cache.get_status(e),
            ExerciseStatus::NotDone | ExerciseStatus::CompileError | ExerciseStatus::TestFail
        )
    });

    match current {
        Some(exercise) => {
            let status = cache.get_status(exercise);

            // Check if we moved to a new exercise
            if !previous_name.is_empty() && *previous_name != exercise.name {
                println!(
                    "{} Completed {}!\n",
                    "".green().bold(),
                    previous_name.cyan()
                );
            }
            *previous_name = exercise.name.clone();

            // Show exercise header
            println!(
                "{} {}\n",
                "Current exercise:".green().bold(),
                exercise.name.cyan()
            );

            // Show file path (absolute)
            let abs_path = std::env::current_dir()
                .map(|cwd| cwd.join(&exercise.path))
                .unwrap_or_else(|_| exercise.path.clone());
            println!("  File: {}", abs_path.display().to_string().dimmed());

            // Show status with details
            match status {
                ExerciseStatus::NotDone => {
                    println!("  Status: {}\n", "Waiting for you to start...".yellow());

                    // Show exercise description
                    if let Ok(content) = std::fs::read_to_string(&exercise.path) {
                        let header: Vec<&str> = content
                            .lines()
                            .take_while(|l| l.starts_with('#'))
                            .filter(|l| !l.contains("I AM NOT DONE"))
                            .collect();
                        for line in header {
                            println!("  {}", line.dimmed());
                        }
                    }

                    println!();
                    println!(
                        "  {}",
                        "Delete the '# I AM NOT DONE' line when you've solved it.".yellow()
                    );
                }
                ExerciseStatus::CompileError => {
                    println!("  Status: {}\n", "Compile Error".red().bold());

                    if let Err(e) = runner::compile(&exercise.path) {
                        // Show first few lines of error
                        for line in e.lines().take(15) {
                            println!("  {}", line.red());
                        }
                    }
                }
                ExerciseStatus::TestFail => {
                    println!("  Status: {}\n", "Tests Failed".red().bold());

                    match runner::run_tests(&exercise.path) {
                        Ok(output) | Err(output) => {
                            for line in output.lines().take(20) {
                                if line.contains("FAIL") || line.contains("panicked") {
                                    println!("  {}", line.red());
                                } else if line.contains("ok") {
                                    println!("  {}", line.green());
                                } else {
                                    println!("  {}", line);
                                }
                            }
                        }
                    }
                }
                ExerciseStatus::Done => {
                    // Shouldn't happen in this branch, but handle it
                    println!("  Status: {}", "Done".green());
                }
            }

            println!();
            println!(
                "  {} seqlings hint",
                "Hint:".cyan()
            );
            show_progress(exercises, cache);
        }
        None => {
            // All done!
            clear_screen();
            println!("\n{}", "=".repeat(50).green());
            println!(
                "{}",
                "  Congratulations! You've completed all exercises!".green().bold()
            );
            println!("{}\n", "=".repeat(50).green());
            show_progress(exercises, cache);
            println!("\n{}", "You're now a Seq programmer!".cyan().bold());
            process::exit(0);
        }
    }
}

/// Open exercise in editor (alternative to watch mode)
#[allow(dead_code)]
fn cmd_run(exercises: &[Exercise]) {
    let mut cache = StatusCache::new();

    // Find first incomplete exercise
    let current = exercises.iter().find(|e| {
        matches!(
            cache.get_status(e),
            ExerciseStatus::NotDone | ExerciseStatus::CompileError | ExerciseStatus::TestFail
        )
    });

    match current {
        Some(exercise) => {
            let status = cache.get_status(exercise);
            println!(
                "\n{} {}\n",
                "Current exercise:".green().bold(),
                exercise.name.cyan()
            );
            println!("  Path: {}", exercise.path.display());
            println!("  Status: {}", format_status(&status));
            println!();

            // Show the exercise description
            if let Ok(content) = std::fs::read_to_string(&exercise.path) {
                // Extract comment header
                let header: Vec<&str> = content
                    .lines()
                    .take_while(|l| l.starts_with('#'))
                    .collect();
                for line in header {
                    println!("  {}", line.dimmed());
                }
            }

            println!();
            println!(
                "{}",
                "Open this file in your editor to complete the exercise.".yellow()
            );
            println!(
                "Run {} to see a hint.",
                "seqlings hint".cyan()
            );
            println!();

            // Open in $EDITOR if set
            if let Ok(editor) = std::env::var("EDITOR") {
                println!("Opening in {}...", editor.cyan());
                let cmd_status = process::Command::new(&editor)
                    .arg(&exercise.path)
                    .status();

                match cmd_status {
                    Ok(s) if s.success() => {
                        // After editor closes, verify the exercise
                        println!();
                        verify_exercise(exercise);
                    }
                    Ok(_) => {
                        eprintln!("{}", "Editor exited with error".red());
                    }
                    Err(e) => {
                        eprintln!("{} {}", "Failed to open editor:".red(), e);
                    }
                }
            } else {
                println!(
                    "{}",
                    "Set $EDITOR environment variable to open exercises automatically.".dimmed()
                );
            }
        }
        None => {
            println!(
                "\n{}",
                "Congratulations! You've completed all exercises!".green().bold()
            );
            show_progress(exercises, &mut cache);
        }
    }
}

/// List all exercises
fn cmd_list(exercises: &[Exercise]) {
    let mut cache = StatusCache::new();

    println!("\n{}\n", "Seqlings Exercises".green().bold());

    let mut current_topic = String::new();
    for exercise in exercises {
        // Extract topic from path
        let topic = exercise
            .path
            .parent()
            .and_then(|p| p.file_name())
            .and_then(|s| s.to_str())
            .unwrap_or("unknown");

        if topic != current_topic {
            println!("\n  {}", topic.cyan().bold());
            current_topic = topic.to_string();
        }

        let status = cache.get_status(exercise);
        let status_icon = match status {
            ExerciseStatus::Done => "".green(),
            ExerciseStatus::NotDone => "".yellow(),
            ExerciseStatus::CompileError => "".red(),
            ExerciseStatus::TestFail => "".red(),
        };

        println!("    {} {}", status_icon, exercise.name);
    }

    println!();
    show_progress(exercises, &mut cache);
}

/// Show hint for an exercise
fn cmd_hint(exercises: &[Exercise], name: Option<String>) {
    let mut cache = StatusCache::new();
    let name_provided = name.is_some();
    let exercise = match &name {
        Some(n) => exercises.iter().find(|e| &e.name == n),
        None => exercises.iter().find(|e| {
            matches!(
                cache.get_status(e),
                ExerciseStatus::NotDone | ExerciseStatus::CompileError | ExerciseStatus::TestFail
            )
        }),
    };

    match exercise {
        Some(ex) => {
            // Construct hint path
            let hint_path = ex.hint_path();
            if hint_path.exists() {
                match std::fs::read_to_string(&hint_path) {
                    Ok(content) => {
                        println!("\n{} {}\n", "Hint for".green(), ex.name.cyan());
                        println!("{}", content);
                    }
                    Err(e) => {
                        eprintln!("{} {}", "Error reading hint:".red(), e);
                    }
                }
            } else {
                println!(
                    "\n{} {}",
                    "No hint available for".yellow(),
                    ex.name.cyan()
                );
                println!("Hint file not found: {}", hint_path.display());
            }
        }
        None => {
            if name_provided {
                eprintln!("{}", "Exercise not found".red());
            } else {
                println!("{}", "All exercises complete! No hints needed.".green());
            }
        }
    }
}

/// Reset an exercise
fn cmd_reset(exercises: &[Exercise], name: Option<String>) {
    let mut cache = StatusCache::new();
    let exercise = match name {
        Some(n) => exercises.iter().find(|e| e.name == n),
        None => exercises.iter().find(|e| {
            matches!(
                cache.get_status(e),
                ExerciseStatus::NotDone | ExerciseStatus::CompileError | ExerciseStatus::TestFail
            )
        }),
    };

    match exercise {
        Some(ex) => {
            let solution_path = ex.solution_path();
            if solution_path.exists() {
                // Read the original (which we store inverted - solution has the answer)
                // For reset, we need the original broken version
                // TODO: Store originals separately, for now just add back # NOT DONE
                match std::fs::read_to_string(&ex.path) {
                    Ok(mut content) => {
                        if !content.contains("# NOT DONE") {
                            // Add marker back after the header comments
                            let insert_pos = content
                                .lines()
                                .take_while(|l| l.starts_with('#'))
                                .map(|l| l.len() + 1)
                                .sum::<usize>();
                            content.insert_str(insert_pos, "\n# NOT DONE\n");
                            if std::fs::write(&ex.path, content).is_ok() {
                                println!("{} {}", "Reset".green(), ex.name.cyan());
                            }
                        } else {
                            println!("{} is already in incomplete state", ex.name.cyan());
                        }
                    }
                    Err(e) => eprintln!("{} {}", "Error reading exercise:".red(), e),
                }
            } else {
                println!(
                    "{}",
                    "No original version found. Cannot reset.".yellow()
                );
            }
        }
        None => {
            eprintln!("{}", "Exercise not found".red());
        }
    }
}

/// Verify all exercises
fn cmd_verify(exercises: &[Exercise]) {
    let mut cache = StatusCache::new();

    println!("\n{}\n", "Verifying all exercises...".green().bold());

    for exercise in exercises {
        let status = cache.get_status(exercise);
        let status_str = format_status(&status);
        let icon = match status {
            ExerciseStatus::Done => "".green(),
            _ => "".red(),
        };
        println!("  {} {} - {}", icon, exercise.name, status_str);
    }

    println!();
    show_progress(exercises, &mut cache);
}

/// Skip to next exercise
fn cmd_next(exercises: &[Exercise]) {
    let mut cache = StatusCache::new();

    // Find current incomplete
    let current_idx = exercises.iter().position(|e| {
        matches!(
            cache.get_status(e),
            ExerciseStatus::NotDone | ExerciseStatus::CompileError | ExerciseStatus::TestFail
        )
    });

    match current_idx {
        Some(idx) if idx + 1 < exercises.len() => {
            let next = &exercises[idx + 1];
            println!("Skipping to: {}", next.name.cyan());
            // Mark current as done by removing # NOT DONE
            // (This is a skip, not a completion)
        }
        _ => {
            println!("{}", "No more exercises to skip to.".yellow());
        }
    }
}

/// Verify a single exercise and show result
#[allow(dead_code)]
fn verify_exercise(exercise: &Exercise) {
    let mut cache = StatusCache::new();
    let status = cache.get_status(exercise);
    println!(
        "{} {}",
        "Exercise status:".bold(),
        format_status(&status)
    );

    match status {
        ExerciseStatus::Done => {
            println!("{}", "Great job! Run 'seqlings' to continue.".green());
        }
        ExerciseStatus::CompileError => {
            // Try to compile and show error
            if let Err(e) = runner::compile(&exercise.path) {
                println!("\n{}\n{}", "Compile error:".red(), e);
            }
        }
        ExerciseStatus::TestFail => {
            // Try to run and show failure
            match runner::run_tests(&exercise.path) {
                Ok(output) => println!("\n{}\n{}", "Test output:".yellow(), output),
                Err(e) => println!("\n{}\n{}", "Test error:".red(), e),
            }
        }
        ExerciseStatus::NotDone => {
            println!(
                "{}",
                "Remove '# NOT DONE' when you've completed the exercise.".yellow()
            );
        }
    }
}

fn format_status(status: &ExerciseStatus) -> colored::ColoredString {
    match status {
        ExerciseStatus::Done => "Done".green(),
        ExerciseStatus::NotDone => "Not Done".yellow(),
        ExerciseStatus::CompileError => "Compile Error".red(),
        ExerciseStatus::TestFail => "Test Failed".red(),
    }
}

fn show_progress(exercises: &[Exercise], cache: &mut StatusCache) {
    let done = exercises
        .iter()
        .filter(|e| matches!(cache.get_status(e), ExerciseStatus::Done))
        .count();
    let total = exercises.len();
    let pct = (done as f64 / total as f64 * 100.0) as usize;

    let bar_width = 30;
    let filled = (done * bar_width) / total;
    let empty = bar_width - filled;

    println!(
        "Progress: [{}{}] {}/{} ({}%)",
        "=".repeat(filled).green(),
        "-".repeat(empty),
        done,
        total,
        pct
    );
}