helixir 0.1.9

Interactive CLI tutorial for learning HelixDB
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
use crate::Lesson;
use crate::formatter::HelixFormatter;
use crate::lessons::get_lesson;
use crate::ui::{clear_screen, display_lesson, get_user_input};
use crate::validation::{
    ParsedQueries, ParsedSchema, QueryValidator, check_helix_init, get_completed_lessons,
    get_current_lesson, mark_lesson_completed, redeploy_instance,
    save_current_lesson,
};
use colored::*;
use std::collections::HashMap;
use std::process::Command;

pub enum ActionResult {
    Continue,
    ChangeTo(usize),
    Exit,
}

pub enum MenuAction {
    Next,
    Back,
    Help,
    Check,
    Quit,
    GoToLesson(usize),
    RunPreviousLessons,
    ShowProgress,
}

pub struct App {
    /// In the format of `lesson_number: { query_answer: String, hql_answer: String }`
    lessons: HashMap<u32, Lesson>,
    current_lesson: usize,
    max_lessons: usize,
    formatter: HelixFormatter,
    output_messages: Vec<String>,
}

impl App {
    pub fn new(lessons: HashMap<u32, Lesson>) -> Self {
        let max_lessons = 24;

        Self {
            lessons,
            current_lesson: 0,
            max_lessons,
            formatter: HelixFormatter::new(),
            output_messages: Vec::new(),
        }
    }

    pub fn get_lesson_answers(&self, lesson_number: u32) -> Option<&Lesson> {
        self.lessons.get(&lesson_number)
    }

    pub fn initialize(&mut self) {
        self.formatter.display_welcome();
        if check_helix_init() {
            self.current_lesson = get_current_lesson();
            self.show_welcome_menu(true);
        } else {
            self.show_welcome_menu(false);
        }
    }

    pub fn run(&mut self) {
        self.initialize();
        let initial_selection = self.get_welcome_input();
        self.handle_welcome_selection(initial_selection);

        let runtime = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime");
        loop {
            let command = get_user_input();
            let action = self.parse_command(&command);
            match action {
                Ok(action) => {
                    self.clear_output();
                    let result = runtime.block_on(self.handle_action(action));
                    match result {
                        ActionResult::Continue => {
                            self.display_current_lesson();
                        }
                        ActionResult::ChangeTo(new_lesson) => {
                            self.current_lesson = new_lesson;
                            let _ = save_current_lesson(self.current_lesson);
                            self.clear_output();
                            self.display_current_lesson();
                        }
                        ActionResult::Exit => {
                            self.formatter.display_info("Thanks for using Helixir :)");
                            break;
                        }
                    }
                }
                Err(error) => {
                    clear_screen();
                    self.clear_output();
                    self.add_output(format!("[ERROR] {}", error));
                    self.display_current_lesson();
                }
            }
        }
    }

    fn parse_command(&self, input: &str) -> Result<MenuAction, String> {
        let trimmed = input.trim();

        if self.current_lesson == 0 && trimmed == "helix init" {
            let output = Command::new("helix").arg("init").output();
            match output {
                Ok(result) => {
                    if result.status.success() {
                        return Ok(MenuAction::Check);
                    } else {
                        println!("Helix init command completed, but check if it was successful.");
                        return Ok(MenuAction::Check);
                    }
                }
                Err(_) => {
                    println!("Please install helix-db and it's CLI");
                    return Err("helix init failed - HelixDB CLI not installed".to_string());
                }
            }
        }

        match trimmed.to_lowercase().as_str() {
            "c" => Ok(MenuAction::Check),
            "h" => Ok(MenuAction::Help),
            "n" => Ok(MenuAction::Next),
            "b" => Ok(MenuAction::Back),
            "q" => Ok(MenuAction::Quit),
            "p" => Ok(MenuAction::ShowProgress),
            "r" => Ok(MenuAction::RunPreviousLessons),
            cmd if cmd.starts_with("g ") => {
                let lesson_str = cmd.strip_prefix("g ").unwrap();
                match lesson_str.parse::<usize>() {
                    Ok(lesson_id) if lesson_id <= self.max_lessons => {
                        Ok(MenuAction::GoToLesson(lesson_id))
                    }
                    Ok(_) => Err(format!(
                        "Lesson {} is out of range (0-{})",
                        lesson_str, self.max_lessons
                    )),
                    Err(_) => Err(format!("Invalid lesson number: {}", lesson_str)),
                }
            }
            _ => Err(format!("Invalid command: {}", input)),
        }
    }

    async fn handle_action(&mut self, action: MenuAction) -> ActionResult {
        match action {
            MenuAction::Back => {
                if self.current_lesson == 0 {
                    clear_screen();
                    self.add_output(
                        "You are already at the first lesson, you cant go back any further."
                            .to_string(),
                    );
                    return ActionResult::Continue;
                }
                clear_screen();
                ActionResult::ChangeTo(self.current_lesson - 1)
            }
            MenuAction::Check => {
                clear_screen();
                let _lesson = get_lesson(self.current_lesson);

                if self.current_lesson >= 5 {
                    let expected_hql = self
                        .get_lesson_answers(self.current_lesson as u32)
                        .map(|answers| answers.hql_answer.as_str())
                        .expect("Lesson HQL data should be compiled into binary");

                    match (
                        ParsedQueries::from_file("db/queries.hx"),
                        ParsedQueries::from_string(expected_hql),
                    ) {
                        (Ok(user_queries), Ok(expected_queries)) => {
                            let validation_result =
                                user_queries.validate_against(&expected_queries);

                            if !validation_result.is_correct {
                                self.add_output("[INCORRECT] Query validation failed. Please fix your queries.hx file".to_string());

                                if !validation_result.missing_queries.is_empty() {
                                    self.add_output(format!(
                                        "[ERROR] Missing queries: {:?}",
                                        validation_result.missing_queries
                                    ));
                                }
                                if !validation_result.extra_queries.is_empty() {
                                    self.add_output(format!(
                                        "[ERROR] Extra queries: {:?}",
                                        validation_result.extra_queries
                                    ));
                                }
                                for (query_name, error) in &validation_result.query_errors {
                                    self.add_output(format!(
                                        "[ERROR] Query '{}': {}",
                                        query_name, error
                                    ));
                                }
                                return ActionResult::Continue;
                            }
                            self.add_output(
                                "[CORRECT] Query structure validation passed".to_string(),
                            );
                        }
                        (Err(e), _) => {
                            self.add_output(format!(
                                "[ERROR] Could not parse your queries.hx file: {}",
                                e
                            ));
                            return ActionResult::Continue;
                        }
                        (_, Err(e)) => {
                            self.add_output(format!(
                                "[ERROR] Could not parse expected queries file: {}",
                                e
                            ));
                            return ActionResult::Continue;
                        }
                    }

                    self.add_output("Deploying queries to cluster...".to_string());
                    if !redeploy_instance() {
                        self.add_output(
                            "[ERROR] Cannot proceed without successful deployment".to_string(),
                        );
                        return ActionResult::Continue;
                    }
                    self.add_output("Running database queries...".to_string());

                    let lesson_data = self
                        .get_lesson_answers(self.current_lesson as u32)
                        .map(|answers| &answers.query_answer)
                        .expect("Lesson answer data should be compiled into binary");
                    let lesson_json: serde_json::Value = serde_json::from_str(lesson_data).unwrap();

                    let queries = lesson_json["queries"].as_array().unwrap();
                    for (index, query_test) in queries.iter().enumerate() {
                        let query_name = query_test["query_name"].as_str().unwrap();
                        let input = query_test["input"].clone();

                        self.add_output(format!(
                            "Testing query {} of {}: {}",
                            index + 1,
                            queries.len(),
                            query_name
                        ));
                        let query_instance: QueryValidator = QueryValidator::new();
                        let comparison =
                            query_instance.execute_and_compare(query_name, input).await;
                        match comparison {
                            Ok((success, message)) => {
                                let status = if success { "[CORRECT]" } else { "[INCORRECT]" };
                                self.add_output(format!(
                                    "{} Query {}: {}",
                                    status, query_name, message
                                ));
                                if !success {
                                    return ActionResult::Continue;
                                }
                            }
                            Err(e) => {
                                let error_msg = e.to_string();
                                if error_msg.contains("error decoding response body") {
                                    self.add_output(format!(
                                        "[ERROR] Deserialization error in query {}: {}",
                                        query_name, error_msg
                                    ));
                                    self.add_output(
                                        "[ERROR] Check if server response format matches lesson_types.rs structures".to_string()
                                    );
                                } else {
                                    self.add_output(format!(
                                        "[ERROR] Query execution failed: {}",
                                        error_msg
                                    ));
                                }
                                return ActionResult::Continue;
                            }
                        }
                    }
                    let _ = mark_lesson_completed(self.current_lesson);
                    self.add_output("[CORRECT] Lesson completed! Great job!".to_string());
                    return ActionResult::Continue;
                }

                if self.current_lesson >= 1 && self.current_lesson <= 4 {
                    let expected_hql = self
                        .get_lesson_answers(self.current_lesson as u32)
                        .map(|answers| answers.hql_answer.as_str())
                        .expect("Lesson HQL data should be compiled into binary");

                    match (
                        ParsedSchema::from_file("db/schema.hx"),
                        ParsedSchema::from_string(expected_hql),
                    ) {
                        (Ok(user_schema), Ok(expected_schema)) => {
                            let result = user_schema.validate_answer(&expected_schema);

                            if result.is_correct {
                                let _ = mark_lesson_completed(self.current_lesson);
                                self.add_output(
                                    "[CORRECT] Schema passed, good job! Lesson completed!"
                                        .to_string(),
                                );
                            } else {
                                self.add_output(
                                    "[INCORRECT] Try again! Here is what might be wrong:"
                                        .to_string(),
                                );

                                if !result.missing_nodes.is_empty() {
                                    self.add_output(format!(
                                        "[ERROR] Missing nodes: {:?}",
                                        result.missing_nodes
                                    ));
                                }
                                if !result.property_errors.is_empty() {
                                    self.add_output("[ERROR] Property errors:".to_string());
                                    for (node, errors) in &result.property_errors {
                                        self.add_output(format!("[ERROR] Node '{}': ", node));
                                        if !errors.missing.is_empty() {
                                            self.add_output(format!(
                                                "[ERROR] Missing properties: {:?}",
                                                errors.missing
                                            ));
                                        }
                                        if !errors.extra.is_empty() {
                                            self.add_output(format!(
                                                "[ERROR] Extra properties: {:?}",
                                                errors.extra
                                            ));
                                        }
                                        if !errors.wrong_type.is_empty() {
                                            self.add_output(
                                                "[ERROR] Property type errors:".to_string(),
                                            );
                                            for (prop_name, expected_type, actual_type) in
                                                &errors.wrong_type
                                            {
                                                self.add_output(format!(
                                                    "[ERROR] Property '{}' has wrong type: expected '{}', got '{}'",
                                                    prop_name, expected_type, actual_type
                                                ));
                                            }
                                        }
                                    }
                                }

                                if !result.missing_edges.is_empty() {
                                    self.add_output(format!(
                                        "[ERROR] Missing edges: {:?}",
                                        result.missing_edges
                                    ));
                                }
                                if !result.edge_errors.is_empty() {
                                    self.add_output("[ERROR] Edge errors:".to_string());
                                    for (edge, errors) in &result.edge_errors {
                                        self.add_output(format!("[ERROR] Edge '{}': ", edge));
                                        if let Some((user_from, expected_from)) =
                                            &errors.from_type_mismatch
                                        {
                                            self.add_output(format!(
                                                "[ERROR] From type mismatch: expected '{}', got '{}'",
                                                expected_from, user_from
                                            ));
                                        }
                                        if let Some((user_to, expected_to)) =
                                            &errors.to_type_mismatch
                                        {
                                            self.add_output(format!(
                                                "[ERROR] To type mismatch: expected '{}', got '{}'",
                                                expected_to, user_to
                                            ));
                                        }
                                        if !errors.property_errors.missing.is_empty() {
                                            self.add_output(format!(
                                                "[ERROR] Missing properties: {:?}",
                                                errors.property_errors.missing
                                            ));
                                        }
                                        if !errors.property_errors.extra.is_empty() {
                                            self.add_output(format!(
                                                "[ERROR] Extra properties: {:?}",
                                                errors.property_errors.extra
                                            ));
                                        }
                                    }
                                }

                                if !result.missing_vectors.is_empty() {
                                    self.add_output(format!(
                                        "[ERROR] Missing vectors: {:?}",
                                        result.missing_vectors
                                    ));
                                }
                                if !result.vector_errors.is_empty() {
                                    self.add_output("[ERROR] Vector errors:".to_string());
                                    for (vector, errors) in &result.vector_errors {
                                        self.add_output(format!("[ERROR] Vector '{}': ", vector));
                                        if !errors.missing.is_empty() {
                                            self.add_output(format!(
                                                "[ERROR] Missing properties: {:?}",
                                                errors.missing
                                            ));
                                        }
                                        if !errors.extra.is_empty() {
                                            self.add_output(format!(
                                                "[ERROR] Extra properties: {:?}",
                                                errors.extra
                                            ));
                                        }
                                        if !errors.wrong_type.is_empty() {
                                            self.add_output(
                                                "[ERROR] Property type errors:".to_string(),
                                            );
                                            for (prop_name, expected_type, actual_type) in
                                                &errors.wrong_type
                                            {
                                                self.add_output(format!(
                                                    "[ERROR] Property '{}' has wrong type: expected '{}', got '{}'",
                                                    prop_name, expected_type, actual_type
                                                ));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        (Err(e), _) => {
                            self.add_output(format!("[ERROR] Could not load your schema: {}", e))
                        }
                        (_, Err(e)) => self
                            .add_output(format!("[ERROR] Could not load expected schema: {}", e)),
                    }
                    return ActionResult::Continue;
                } else if self.current_lesson == 0 {
                    match Command::new("helix").arg("check").output() {
                        Ok(output) if output.status.success() => {
                            let _ = mark_lesson_completed(self.current_lesson);
                            self.add_output(
                                "[CORRECT] Helix initialization completed! Lesson completed!"
                                    .to_string(),
                            );
                            return ActionResult::ChangeTo(self.current_lesson + 1);
                        }
                        _ => {
                            self.add_output(
                                "Helix initialization: Run 'helix init' to continue".to_string(),
                            );
                            return ActionResult::Continue;
                        }
                    }
                } else {
                    return ActionResult::Continue;
                }
            }
            MenuAction::Help => {
                clear_screen();
                let lesson_hints = get_lesson(self.current_lesson).hints;
                self.formatter.print_hints(&lesson_hints);
                ActionResult::Continue
            }
            MenuAction::Next => {
                if self.current_lesson >= self.max_lessons {
                    clear_screen();
                    self.add_output(
                        "You are already at the last lesson, you cant go any further.".to_string(),
                    );
                    return ActionResult::Continue;
                }
                clear_screen();
                ActionResult::ChangeTo(self.current_lesson + 1)
            }
            MenuAction::Quit => ActionResult::Exit,
            MenuAction::GoToLesson(lesson_id) => {
                clear_screen();
                if lesson_id <= self.max_lessons {
                    self.add_output(format!("Jumping to lesson {}", lesson_id));
                    ActionResult::ChangeTo(lesson_id)
                } else {
                    self.add_output(format!(
                        "[ERROR] Lesson {} does not exist (max: {})",
                        lesson_id, self.max_lessons
                    ));
                    ActionResult::Continue
                }
            }
            MenuAction::ShowProgress => {
                clear_screen();
                self.show_progress();
                ActionResult::Continue
            }
            MenuAction::RunPreviousLessons => {
                clear_screen();
                self.run_previous_lessons().await
            }
        }
    }
    fn clear_output(&mut self) {
        self.output_messages.clear();
    }
    fn add_output(&mut self, message: String) {
        self.output_messages.push(message);
    }
    fn display_current_lesson(&self) {
        let lesson = get_lesson(self.current_lesson);
        if self.output_messages.is_empty() {
            self.formatter
                .display_lesson(&lesson.title, lesson.id, &lesson.instructions);
        } else {
            self.formatter.display_lesson_with_output(
                &lesson.title,
                lesson.id,
                &lesson.instructions,
                &self.output_messages,
            );
        }
    }

    fn show_progress(&self) {
        let completed_lessons = get_completed_lessons();
        let total_lessons = self.max_lessons + 1;

        self.formatter.display_info(&format!(
            "Progress: {} / {} lessons completed",
            completed_lessons.len(),
            total_lessons
        ));
        self.formatter
            .display_info(&format!("Current lesson: {}", self.current_lesson));

        if !completed_lessons.is_empty() {
            println!("{}", "Completed lessons:".bright_green().bold());
            for lesson_id in completed_lessons {
                let lesson = get_lesson(lesson_id);
                println!("  {} - {}", lesson_id, lesson.title.bright_white());
            }
        } else {
            println!("{}", "No lessons completed yet.".bright_yellow());
        }
        println!();
    }

    async fn run_previous_lessons(&self) -> ActionResult {
        if self.current_lesson == 0 {
            self.formatter.display_info("No previous lessons to run.");
            return ActionResult::Continue;
        }

        self.formatter.display_info(&format!(
            "Running all lessons before lesson {}...",
            self.current_lesson
        ));

        for lesson_id in 0..self.current_lesson {
            let lesson = get_lesson(lesson_id);

            if lesson_id < 5 {
                continue;
            }

            self.formatter
                .display_info(&format!("Running lesson {}: {}", lesson_id, lesson.title));

            if lesson_id >= 5 {
                if !redeploy_instance() {
                    self.formatter
                        .display_error(&format!("Failed to compile for lesson {}", lesson_id));
                    continue;
                }

                let lesson_data = self
                    .get_lesson_answers(lesson_id as u32)
                    .map(|answers| answers.query_answer.clone())
                    .unwrap_or_else(|| {
                        self.formatter.display_error(&format!(
                            "No compiled lesson data found for lesson {}",
                            lesson_id
                        ));
                        String::new()
                    });

                if lesson_data.is_empty() {
                    continue;
                }

                let lesson_json: serde_json::Value = match serde_json::from_str(&lesson_data) {
                    Ok(json) => json,
                    Err(e) => {
                        self.formatter.display_error(&format!(
                            "Could not parse lesson {} JSON: {}",
                            lesson_id, e
                        ));
                        continue;
                    }
                };

                if let Some(queries) = lesson_json["queries"].as_array() {
                    for query_test in queries {
                        let query_name = query_test["query_name"].as_str().unwrap_or("unknown");
                        let input = query_test["input"].clone();

                        let query_instance = QueryValidator::new();
                        match query_instance.execute_and_compare(query_name, input).await {
                            Ok((success, message)) => {
                                if success {
                                    println!("  {} {}", "[OK]".bright_green().bold(), query_name);
                                } else {
                                    self.formatter.display_error(&format!(
                                        "Query {} failed: {}",
                                        query_name, message
                                    ));
                                }
                            }
                            Err(e) => {
                                self.formatter
                                    .display_error(&format!("Query {} error: {}", query_name, e));
                            }
                        }
                    }
                }
            }
            let _ = mark_lesson_completed(lesson_id);
        }

        self.formatter
            .display_validation_result(true, "All previous lessons executed successfully!");
        ActionResult::Continue
    }
    fn show_welcome_menu(&self, has_progress: bool) {
        println!();
        if has_progress {
            println!(
                "{}",
                "  What would you like to do?"
                    .truecolor(202, 211, 245)
                    .bold()
            );
            println!();
            println!(
                "{} {}",
                "  1)".truecolor(166, 218, 149).bold(),
                format!("Resume from lesson {}", self.current_lesson).truecolor(184, 192, 224)
            );
            println!(
                "{} {}",
                "  2)".truecolor(166, 218, 149).bold(),
                "Go to specific lesson".truecolor(184, 192, 224)
            );
            println!(
                "{} {}",
                "  3)".truecolor(166, 218, 149).bold(),
                "Start from beginning".truecolor(184, 192, 224)
            );
        } else {
            println!(
                "{}",
                "  What would you like to do?"
                    .truecolor(202, 211, 245)
                    .bold()
            );
            println!();
            println!(
                "{} {}",
                "  1)".truecolor(166, 218, 149).bold(),
                "Get started (Lesson 0)".truecolor(184, 192, 224)
            );
            println!(
                "{} {}",
                "  2)".truecolor(166, 218, 149).bold(),
                "Go to specific lesson".truecolor(184, 192, 224)
            );
        }
        println!();
        print!(
            "{}",
            "  Enter your choice: ".truecolor(184, 192, 224).bold()
        );
    }
    fn get_welcome_input(&self) -> String {
        use std::io::{self, Write};
        io::stdout().flush().unwrap();
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap();
        input.trim().to_string()
    }
    fn handle_welcome_selection(&mut self, selection: String) {
        clear_screen();

        match selection.as_str() {
            "1" => {
                if check_helix_init() {
                    display_lesson(self.current_lesson);
                } else {
                    self.current_lesson = 0;
                    display_lesson(self.current_lesson);
                }
            }
            "2" => {
                print!("{}", "Enter lesson number: ".bright_yellow());
                use std::io::{self, Write};
                io::stdout().flush().unwrap();
                let mut input = String::new();
                io::stdin().read_line(&mut input).unwrap();

                if let Ok(lesson_num) = input.trim().parse::<usize>() {
                    if lesson_num <= self.max_lessons {
                        self.current_lesson = lesson_num;
                        let _ = save_current_lesson(self.current_lesson);
                        clear_screen();
                        display_lesson(self.current_lesson);
                    } else {
                        println!(
                            "{}",
                            format!("Invalid lesson number. Max lesson is {}", self.max_lessons)
                                .bright_red()
                        );
                        self.current_lesson = 0;
                        display_lesson(self.current_lesson);
                    }
                } else {
                    println!("{}", "Invalid input. Starting from lesson 0.".bright_red());
                    self.current_lesson = 0;
                    display_lesson(self.current_lesson);
                }
            }
            "3" if check_helix_init() => {
                self.current_lesson = 0;
                let _ = save_current_lesson(self.current_lesson);
                display_lesson(self.current_lesson);
            }
            _ => {
                println!("{}", "Invalid choice. Starting from lesson 0.".bright_red());
                self.current_lesson = 0;
                display_lesson(self.current_lesson);
            }
        }
    }
}