KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical equilibrium, chemical engeneering
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
use super::test_options::TestOptions;
use eframe::egui;

use std::ops::Range;
use std::path::{Path, PathBuf};

fn contextual_help_request_id() -> egui::Id {
    egui::Id::unique("experimental_kinetics_contextual_help")
}

pub(crate) fn contextual_help_link(ui: &mut egui::Ui, topic: &'static str) {
    if ui
        .small_button("? Help")
        .on_hover_text(format!(
            "Open the Help article for {topic}; this form stays open."
        ))
        .clicked()
    {
        ui.ctx()
            .data_mut(|data| data.insert_temp(contextual_help_request_id(), topic.to_owned()));
    }
}

#[derive(Clone, Debug)]
pub struct HelpSectionNode {
    section_index: usize,
    children: Vec<usize>,
}

#[derive(Clone, Debug, Default)]
pub(crate) struct HelpDoc {
    pub(crate) raw_markdown: String,
    pub(crate) blocks: Vec<HelpBlock>,
    pub(crate) sections: Vec<HelpSection>,
}

#[derive(Clone, Debug, Default)]
pub(crate) struct HelpSection {
    pub(crate) title: String,
    pub(crate) level: usize,
    pub(crate) block_range: Range<usize>,
    pub(crate) search_blob: String,
}

#[derive(Clone, Debug, Default)]
pub(crate) enum HelpBlock {
    #[default]
    Empty,
    Heading {
        level: usize,
        text: String,
    },
    Paragraph(String),
    BulletList(Vec<String>),
    CodeBlock(String),
    Image {
        alt: String,
        path: String,
    },
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
pub(crate) enum HelpLanguage {
    #[default]
    Eng,
    Rus,
}

impl HelpDoc {
    pub fn hierarchical_sections(&self) -> Vec<HelpSectionNode> {
        let mut result = Vec::new();
        let mut current_parent_idx: Option<usize> = None;

        for (idx, section) in self.sections.iter().enumerate() {
            if section.level == 2 {
                result.push(HelpSectionNode {
                    section_index: idx,
                    children: Vec::new(),
                });
                current_parent_idx = Some(result.len() - 1);
            } else if section.level == 1 {
                if let Some(parent_idx) = current_parent_idx {
                    result[parent_idx].children.push(idx);
                } else {
                    result.push(HelpSectionNode {
                        section_index: idx,
                        children: Vec::new(),
                    });
                    current_parent_idx = Some(result.len() - 1);
                }
            } else {
                // Levels >2 are not considered for top-level hierarchy in current behavior.
                // They can be handled similarly if needed in future.
            }
        }

        result
    }
}

impl HelpLanguage {
    fn file_name(self) -> &'static str {
        match self {
            Self::Eng => "help_eng.md",
            Self::Rus => "help_rus.md",
        }
    }

    fn embedded_markdown(self) -> &'static str {
        match self {
            Self::Eng => include_str!("../../assets/help_eng.md"),
            Self::Rus => include_str!("../../assets/help_rus.md"),
        }
    }

    fn embedded_workflows(self) -> &'static str {
        match self {
            Self::Eng => include_str!("../../assets/help_workflows_eng.md"),
            Self::Rus => include_str!("../../assets/help_workflows_rus.md"),
        }
    }
}

impl TestOptions {
    pub(crate) fn open_requested_contextual_help(&mut self, ctx: &egui::Context) {
        let requested =
            ctx.data_mut(|data| data.remove_temp::<String>(contextual_help_request_id()));
        let Some(topic) = requested else { return };

        if self.parsed_help.sections.is_empty() {
            let _ = self.reload_help();
        }
        self.help_search_query.clear();
        self.help_selected_section = self
            .parsed_help
            .sections
            .iter()
            .position(|section| section.title.to_lowercase().contains(&topic.to_lowercase()));
        self.show_help_window = true;
        self.help_status = Some(format!("Opened Help: {topic}"));
    }

    pub fn show_help_window_ui(&mut self, ctx: &egui::Context) {
        if !self.show_help_window {
            return;
        }

        egui_extras::install_image_loaders(ctx);

        let mut open = self.show_help_window;
        egui::Window::new("Help")
            .open(&mut open)
            .resizable(true)
            .default_width(980.0)
            .default_height(700.0)
            .show(ctx, |ui| {
                self.render_help_toolbar(ui);

                if let Some(err) = &self.help_error {
                    ui.colored_label(egui::Color32::RED, err);
                }
                if let Some(status) = &self.help_status {
                    ui.colored_label(egui::Color32::LIGHT_GREEN, status);
                }

                ui.separator();

                if self.help_edit_mode {
                    self.render_help_editor(ui);
                } else {
                    self.render_help_browser(ui);
                }
            });
        self.show_help_window = open && self.show_help_window;
    }

    fn render_help_toolbar(&mut self, ui: &mut egui::Ui) {
        ui.horizontal_wrapped(|ui| {
            ui.label("Language:");

            if ui
                .selectable_label(self.help_lang == HelpLanguage::Eng, "ENG")
                .clicked()
            {
                self.help_lang = HelpLanguage::Eng;
                let _ = self.reload_help();
            }
            if ui
                .selectable_label(self.help_lang == HelpLanguage::Rus, "RUS")
                .clicked()
            {
                self.help_lang = HelpLanguage::Rus;
                let _ = self.reload_help();
            }

            ui.separator();
            ui.label("Search:");
            let search = ui.add_sized(
                [240.0, 24.0],
                egui::TextEdit::singleline(&mut self.help_search_query)
                    .hint_text("section, command, term..."),
            );
            if search.changed() && self.help_selected_section.is_none() {
                self.help_selected_section = self.filtered_section_indices().first().copied();
            }

            ui.separator();
            if ui.button("Reload").clicked() {
                let _ = self.reload_help();
            }

            if !self.help_edit_mode {
                if ui.button("Edit").clicked() {
                    self.help_edit_mode = true;
                    if self.help_editor_buffer.is_empty() {
                        self.help_editor_buffer = self.parsed_help.raw_markdown.clone();
                    }
                    self.help_status = Some("Edit mode enabled".to_string());
                }
            } else {
                if ui.button("Save").clicked() {
                    if let Err(err) = self.save_help() {
                        self.help_error = Some(err);
                    }
                }
                if ui.button("Cancel").clicked() {
                    self.help_edit_mode = false;
                    self.help_editor_buffer = self.parsed_help.raw_markdown.clone();
                    self.help_status = Some("Changes discarded".to_string());
                }
            }

            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                if ui.button("Close").clicked() {
                    self.show_help_window = false;
                }
            });
        });
    }

    fn render_help_editor(&mut self, ui: &mut egui::Ui) {
        ui.label(format!("Editing: {}", self.current_help_path().display()));
        ui.add_space(6.0);
        egui::ScrollArea::vertical()
            .id_salt("help_editor_scroll")
            .show(ui, |ui| {
                ui.add(
                    egui::TextEdit::multiline(&mut self.help_editor_buffer)
                        .desired_rows(32)
                        .desired_width(f32::INFINITY)
                        .code_editor()
                        .hint_text("Edit Help Markdown")
                        .id_source("help_markdown_editor"),
                );
            });
    }

    fn render_help_browser(&mut self, ui: &mut egui::Ui) {
        let filtered_sections = self.filtered_section_indices();
        if filtered_sections.is_empty() {
            ui.label("No sections match the current search query.");
            return;
        }

        let selected = self
            .help_selected_section
            .filter(|idx| filtered_sections.contains(idx))
            .unwrap_or(filtered_sections[0]);
        self.help_selected_section = Some(selected);

        ui.columns(2, |columns| {
            columns[0].set_min_width(240.0);
            columns[0].heading("Sections");
            columns[0].separator();
            egui::ScrollArea::vertical()
                .id_salt("help_sections_list")
                .show(&mut columns[0], |ui| {
                    if self.help_search_query.trim().is_empty() {
                        for node in self.parsed_help.hierarchical_sections().iter() {
                            let section = &self.parsed_help.sections[node.section_index];
                            let is_open = self.help_expanded_sections.contains(&node.section_index);

                            ui.horizontal(|ui| {
                                if !node.children.is_empty() {
                                    if ui.small_button(if is_open { "-" } else { "+" }).clicked() {
                                        if is_open {
                                            self.help_expanded_sections.remove(&node.section_index);
                                        } else {
                                            self.help_expanded_sections.insert(node.section_index);
                                        }
                                    }
                                } else {
                                    ui.add_space(14.0);
                                }

                                if ui
                                    .selectable_label(
                                        self.help_selected_section == Some(node.section_index),
                                        &section.title,
                                    )
                                    .clicked()
                                {
                                    self.help_selected_section = Some(node.section_index);
                                }
                            });

                            if is_open {
                                for &child_idx in node.children.iter() {
                                    let child = &self.parsed_help.sections[child_idx];
                                    ui.horizontal(|ui| {
                                        ui.add_space(18.0);
                                        if ui
                                            .selectable_label(
                                                self.help_selected_section == Some(child_idx),
                                                &child.title,
                                            )
                                            .clicked()
                                        {
                                            self.help_selected_section = Some(child_idx);
                                        }
                                    });
                                }
                            }
                        }
                    } else {
                        for idx in filtered_sections.iter().copied() {
                            let section = &self.parsed_help.sections[idx];
                            let indent = if section.level > 1 { "  " } else { "" };
                            let label = format!("{indent}{}", section.title);
                            if ui
                                .selectable_label(self.help_selected_section == Some(idx), label)
                                .clicked()
                            {
                                self.help_selected_section = Some(idx);
                            }
                        }
                    }
                });

            columns[1].heading(if self.help_search_query.trim().is_empty() {
                self.parsed_help.sections[selected].title.clone()
            } else {
                format!("Search results: {}", filtered_sections.len())
            });
            columns[1].separator();
            egui::ScrollArea::vertical()
                .id_salt("help_section_content")
                .show(&mut columns[1], |ui| {
                    if self.help_search_query.trim().is_empty() {
                        self.render_section(ui, selected, false);
                    } else {
                        for idx in filtered_sections.iter().copied() {
                            self.render_section(ui, idx, true);
                            ui.add_space(12.0);
                            ui.separator();
                        }
                    }
                });
        });
    }

    fn render_section(&self, ui: &mut egui::Ui, section_index: usize, search_mode: bool) {
        let section = &self.parsed_help.sections[section_index];
        if search_mode {
            ui.label(egui::RichText::new(&section.title).strong().size(24.0));
            ui.add_space(4.0);
        }

        for block in &self.parsed_help.blocks[section.block_range.clone()] {
            if search_mode && !block_matches_query(block, &self.help_search_query) {
                continue;
            }
            render_help_block(ui, block, self.current_help_path().parent());
        }
    }

    pub(crate) fn current_help_path(&self) -> PathBuf {
        PathBuf::from("src/assets").join(self.help_lang.file_name())
    }

    pub(crate) fn reload_help(&mut self) -> Result<(), String> {
        let path = self.current_help_path();
        let (mut contents, source_label) = match std::fs::read_to_string(&path) {
            Ok(contents) => (contents, format!("local override {}", path.display())),
            Err(_) => (
                self.help_lang.embedded_markdown().to_string(),
                "bundled Help".to_string(),
            ),
        };
        let (marker, workflow) = match self.help_lang {
            HelpLanguage::Eng => ("## Typical Workflows", self.help_lang.embedded_workflows()),
            HelpLanguage::Rus => (
                "## Типовые рабочие процессы",
                self.help_lang.embedded_workflows(),
            ),
        };
        if !contents.contains(marker) {
            contents.push_str("\n\n");
            contents.push_str(workflow);
        }
        self.parsed_help = parse_help_markdown(&contents);
        self.help_editor_buffer = contents;
        self.help_error = None;
        self.help_status = Some(format!("Loaded {source_label}"));
        self.help_selected_section = self.filtered_section_indices().first().copied();
        Ok(())
    }

    fn save_help(&mut self) -> Result<(), String> {
        let path = self.current_help_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent).map_err(|err| err.to_string())?;
        }
        std::fs::write(&path, &self.help_editor_buffer).map_err(|err| err.to_string())?;
        self.help_edit_mode = false;
        self.help_status = Some(format!("Saved {}", path.display()));
        self.reload_help()
    }

    fn filtered_section_indices(&self) -> Vec<usize> {
        let query = self.help_search_query.trim();
        if query.is_empty() {
            return (0..self.parsed_help.sections.len()).collect();
        }

        self.parsed_help
            .sections
            .iter()
            .enumerate()
            .filter_map(|(idx, section)| {
                if contains_case_insensitive(&section.search_blob, query) {
                    Some(idx)
                } else {
                    None
                }
            })
            .collect()
    }
}

fn parse_help_markdown(src: &str) -> HelpDoc {
    let mut blocks = Vec::new();
    let mut paragraph_lines: Vec<String> = Vec::new();
    let mut list_items: Vec<String> = Vec::new();
    let mut code_lines: Vec<String> = Vec::new();
    let mut in_code_block = false;

    let flush_paragraph = |blocks: &mut Vec<HelpBlock>, paragraph_lines: &mut Vec<String>| {
        if !paragraph_lines.is_empty() {
            blocks.push(HelpBlock::Paragraph(paragraph_lines.join("\n")));
            paragraph_lines.clear();
        }
    };
    let flush_list = |blocks: &mut Vec<HelpBlock>, list_items: &mut Vec<String>| {
        if !list_items.is_empty() {
            blocks.push(HelpBlock::BulletList(std::mem::take(list_items)));
        }
    };
    let flush_code = |blocks: &mut Vec<HelpBlock>, code_lines: &mut Vec<String>| {
        if !code_lines.is_empty() {
            blocks.push(HelpBlock::CodeBlock(code_lines.join("\n")));
            code_lines.clear();
        }
    };

    for raw_line in src.lines() {
        let line = raw_line.trim_end_matches('\r');
        let trimmed = line.trim();

        if in_code_block {
            if trimmed.starts_with("```") {
                flush_code(&mut blocks, &mut code_lines);
                in_code_block = false;
            } else {
                code_lines.push(line.to_string());
            }
            continue;
        }

        if trimmed.starts_with("```") {
            flush_paragraph(&mut blocks, &mut paragraph_lines);
            flush_list(&mut blocks, &mut list_items);
            in_code_block = true;
            continue;
        }

        if trimmed.is_empty() {
            flush_paragraph(&mut blocks, &mut paragraph_lines);
            flush_list(&mut blocks, &mut list_items);
            continue;
        }

        if let Some((level, text)) = parse_heading(trimmed) {
            flush_paragraph(&mut blocks, &mut paragraph_lines);
            flush_list(&mut blocks, &mut list_items);
            blocks.push(HelpBlock::Heading { level, text });
            continue;
        }

        if let Some((alt, path)) = parse_image(trimmed) {
            flush_paragraph(&mut blocks, &mut paragraph_lines);
            flush_list(&mut blocks, &mut list_items);
            blocks.push(HelpBlock::Image { alt, path });
            continue;
        }

        if let Some(item) = parse_list_item(trimmed) {
            flush_paragraph(&mut blocks, &mut paragraph_lines);
            list_items.push(item);
            continue;
        }

        flush_list(&mut blocks, &mut list_items);
        paragraph_lines.push(line.to_string());
    }

    flush_paragraph(&mut blocks, &mut paragraph_lines);
    flush_list(&mut blocks, &mut list_items);
    flush_code(&mut blocks, &mut code_lines);

    let mut sections = Vec::new();
    let headings: Vec<(usize, usize, String)> = blocks
        .iter()
        .enumerate()
        .filter_map(|(idx, block)| match block {
            HelpBlock::Heading { level, text } if *level <= 2 => Some((idx, *level, text.clone())),
            _ => None,
        })
        .collect();

    if headings.is_empty() {
        sections.push(HelpSection {
            title: "Help".to_string(),
            level: 1,
            block_range: 0..blocks.len(),
            search_blob: blocks
                .iter()
                .map(block_search_text)
                .collect::<Vec<_>>()
                .join("\n"),
        });
    } else {
        for (position, (start_idx, level, title)) in headings.iter().enumerate() {
            let end_idx = headings
                .get(position + 1)
                .map(|(next_idx, _, _)| *next_idx)
                .unwrap_or(blocks.len());
            let blob = blocks[*start_idx..end_idx]
                .iter()
                .map(block_search_text)
                .collect::<Vec<_>>()
                .join("\n");
            sections.push(HelpSection {
                title: title.clone(),
                level: *level,
                block_range: *start_idx..end_idx,
                search_blob: blob,
            });
        }
    }

    HelpDoc {
        raw_markdown: src.to_string(),
        blocks,
        sections,
    }
}

fn parse_heading(line: &str) -> Option<(usize, String)> {
    let level = line.chars().take_while(|ch| *ch == '#').count();
    if !(1..=6).contains(&level) {
        return None;
    }
    let text = line[level..].trim();
    if text.is_empty() {
        None
    } else {
        Some((level, text.to_string()))
    }
}

fn parse_image(line: &str) -> Option<(String, String)> {
    if !line.starts_with("![") {
        return None;
    }
    let alt_end = line.find("](")?;
    let path_end = line.rfind(')')?;
    if path_end <= alt_end + 2 {
        return None;
    }
    Some((
        line[2..alt_end].trim().to_string(),
        line[alt_end + 2..path_end].trim().to_string(),
    ))
}

fn parse_list_item(line: &str) -> Option<String> {
    if let Some(item) = line.strip_prefix("- ") {
        return Some(item.trim().to_string());
    }
    if let Some(item) = line.strip_prefix("* ") {
        return Some(item.trim().to_string());
    }
    let mut chars = line.chars();
    let mut saw_digit = false;
    while let Some(ch) = chars.next() {
        if ch.is_ascii_digit() {
            saw_digit = true;
            continue;
        }
        if ch == '.' && saw_digit {
            let rest = chars.as_str().trim();
            if !rest.is_empty() {
                return Some(rest.to_string());
            }
        }
        break;
    }
    None
}

fn render_help_block(ui: &mut egui::Ui, block: &HelpBlock, base_dir: Option<&Path>) {
    match block {
        HelpBlock::Empty => {}
        HelpBlock::Heading { level, text } => {
            let size = match level {
                1 => 28.0,
                2 => 22.0,
                _ => 18.0,
            };
            ui.add_space(4.0);
            ui.label(egui::RichText::new(text).strong().size(size));
            ui.add_space(2.0);
        }
        HelpBlock::Paragraph(text) => {
            ui.label(text);
            ui.add_space(6.0);
        }
        HelpBlock::BulletList(items) => {
            for item in items {
                ui.horizontal_wrapped(|ui| {
                    ui.label("?");
                    ui.label(item);
                });
            }
            ui.add_space(6.0);
        }
        HelpBlock::CodeBlock(code) => {
            egui::Frame::group(ui.style()).show(ui, |ui| {
                ui.label(egui::RichText::new(code).monospace());
            });
            ui.add_space(6.0);
        }
        HelpBlock::Image { alt, path } => {
            let resolved = resolve_image_path(base_dir, path);
            if resolved.exists() {
                let uri = format!("file://{}", resolved.to_string_lossy().replace('\\', "/"));
                ui.add(
                    egui::Image::from_uri(uri)
                        .alt_text(alt)
                        .shrink_to_fit()
                        .max_height(420.0),
                );
                if !alt.is_empty() {
                    ui.small(alt);
                }
            } else {
                ui.colored_label(
                    egui::Color32::YELLOW,
                    format!("Image not found: {}", resolved.display()),
                );
            }
            ui.add_space(8.0);
        }
    }
}

fn resolve_image_path(base_dir: Option<&Path>, path: &str) -> PathBuf {
    let candidate = PathBuf::from(path);
    if candidate.is_absolute() {
        candidate
    } else if let Some(base_dir) = base_dir {
        base_dir.join(candidate)
    } else {
        candidate
    }
}

fn block_search_text(block: &HelpBlock) -> String {
    match block {
        HelpBlock::Empty => String::new(),
        HelpBlock::Heading { text, .. } => text.clone(),
        HelpBlock::Paragraph(text) => text.clone(),
        HelpBlock::BulletList(items) => items.join("\n"),
        HelpBlock::CodeBlock(code) => code.clone(),
        HelpBlock::Image { alt, path } => format!("{alt}\n{path}"),
    }
}

fn block_matches_query(block: &HelpBlock, query: &str) -> bool {
    let query = query.trim();
    query.is_empty() || contains_case_insensitive(&block_search_text(block), query)
}

fn contains_case_insensitive(haystack: &str, needle: &str) -> bool {
    haystack.to_lowercase().contains(&needle.to_lowercase())
}

#[cfg(test)]
mod workflow_help_tests {
    use super::{HelpLanguage, TestOptions, contextual_help_link};
    use egui_kittest::{Harness, kittest::Queryable};

    #[test]
    fn workflow_help_is_loaded_for_both_languages() {
        for (language, marker, required_text) in [
            (
                HelpLanguage::Eng,
                "Typical Workflows",
                "isothermal temperature metadata",
            ),
            (
                HelpLanguage::Rus,
                "Типовые рабочие процессы",
                "Изотермический опыт",
            ),
        ] {
            let mut options = TestOptions::new();
            options.help_lang = language;
            options.reload_help().unwrap();
            assert!(options.parsed_help.raw_markdown.contains(marker));
            assert!(options.parsed_help.raw_markdown.contains(required_text));
            assert!(
                options
                    .parsed_help
                    .sections
                    .iter()
                    .any(|section| section.title.contains(marker))
            );
            assert!(!options.parsed_help.raw_markdown.contains("РўР"));
            assert!(!options.parsed_help.raw_markdown.contains("РЎР"));
        }
    }

    #[test]
    fn embedded_help_contains_import_paths_and_formula_workflows() {
        for language in [HelpLanguage::Eng, HelpLanguage::Rus] {
            let mut options = TestOptions::new();
            options.help_lang = language;
            options.reload_help().unwrap();
            let text = &options.parsed_help.raw_markdown;
            assert!(text.contains("Import Data"));
            assert!(text.contains("Open Document"));
            assert!(text.contains("LSQ"));
            assert!(text.contains("Simple One-Step Kinetics"));
            assert!(!text.contains("Calculate kinetic expression"));
            assert!(!text.contains("Solve BVP"));
            assert!(!text.contains("(under development)"));
            assert!(!text.contains("# Run Tests"));
            assert!(!text.contains("first supported workflow accepts"));
            assert!(!text.contains("Первая версия принимает"));
            for topic in [
                "Formula Column",
                "Column Manager",
                "Golden Pipeline",
                "LSQ Splines",
                "Fit Model",
                "Hampel filter",
                "Savitzky Golay",
                "Rolling mean",
                "LOWESS",
                "Splines",
                "Isoconversional",
                "Kissinger",
                "Coefficients Handling",
                "Is this a sublimation?",
                "Combined Kinetics Analysis",
            ] {
                assert!(
                    options
                        .parsed_help
                        .sections
                        .iter()
                        .any(|section| section.title.contains(topic)),
                    "missing article for {topic:?} in {language:?}"
                );
            }

            match language {
                HelpLanguage::Eng => {
                    assert!(text.contains("custom parameters are not automatically treated as rate constants"));
                    assert!(text.contains("same coefficient and stage from different experiments"));
                    assert!(text.contains("isothermal experiments at different temperatures"));
                }
                HelpLanguage::Rus => {
                    assert!(text.contains("не объявляются константами скорости автоматически"));
                    assert!(text.contains("один и тот же коэффициент и стадию у разных опытов"));
                    assert!(text.contains("изотермические опыты при разных температурах"));
                }
            }
        }
    }

    #[test]
    fn advanced_workflow_articles_explain_fit_pipeline_and_column_manager_contracts() {
        for language in [HelpLanguage::Eng, HelpLanguage::Rus] {
            let mut options = TestOptions::new();
            options.help_lang = language;
            options.reload_help().unwrap();
            let text = &options.parsed_help.raw_markdown;

            for required in [
                "Limit fit range",
                "Exclude missing interval from fit",
                "Evaluate fitted columns",
                "Add reconstructed experiment",
                "R2",
                "Conversion η min/max",
                "Delete source row",
                "Delete columns",
                "Delete All",
            ] {
                assert!(
                    text.contains(required),
                    "missing workflow guidance {required:?} in {language:?}"
                );
            }

            match language {
                HelpLanguage::Eng => {
                    for required in [
                        "does not merge rows into or change the source",
                        "publishes the result only after every step succeeds",
                        "not a full copy of every input column",
                        "Averaging time is in seconds",
                        "does not interpolate",
                        "not proof that a model is physically correct",
                        "Friedman Integral** is isothermal",
                        "other listed methods are non-isothermal",
                    ] {
                        assert!(
                            text.to_lowercase().contains(&required.to_lowercase()),
                            "missing English guidance {required:?}"
                        );
                    }
                }
                HelpLanguage::Rus => {
                    for required in [
                        "исходный опыт не объединяется",
                        "частичный результат не остаётся",
                        "не полную копию всех входных колонок",
                        "задаётся в секундах",
                        "не интерполирует",
                        "не доказательство точности",
                        "Friedman Integral** — изотермический метод",
                        "остальные методы в списке неизотермические",
                    ] {
                        assert!(
                            text.to_lowercase().contains(&required.to_lowercase()),
                            "missing Russian guidance {required:?}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn help_window_renders_at_compact_size_in_both_languages() {
        for language in [HelpLanguage::Eng, HelpLanguage::Rus] {
            let mut options = TestOptions::new();
            options.help_lang = language;
            options.reload_help().unwrap();
            options.show_help_window = true;
            let mut harness = Harness::new_ui_state(
                |ui, options: &mut TestOptions| options.show_help_window_ui(ui.ctx()),
                options,
            );
            harness.set_size(egui::vec2(680.0, 520.0));
            harness.run();
            assert!(harness.state().show_help_window);
            assert!(harness.query_by_label("Close").is_some());
        }
    }

    #[test]
    fn contextual_help_keeps_language_and_selects_the_requested_article() {
        #[derive(Default)]
        struct OperationForm {
            output_name: String,
        }

        let mut options = TestOptions::new();
        options.help_lang = HelpLanguage::Rus;
        options.reload_help().unwrap();
        let form = OperationForm {
            output_name: "custom_fit".to_string(),
        };
        let mut harness = Harness::new_ui_state(
            |ui, _state: &mut OperationForm| contextual_help_link(ui, "Fit Model"),
            form,
        );

        harness.get_by_label("? Help").click();
        harness.run();
        options.open_requested_contextual_help(&harness.ctx);

        assert_eq!(harness.state().output_name, "custom_fit");
        assert!(options.show_help_window);
        assert_eq!(options.help_lang, HelpLanguage::Rus);
        let section = options
            .help_selected_section
            .and_then(|index| options.parsed_help.sections.get(index))
            .expect("contextual article should exist");
        assert!(section.title.contains("Fit Model"));
    }

    #[test]
    fn coefficients_help_link_opens_the_catalog_and_arrhenius_guidance() {
        #[derive(Default)]
        struct CoefficientsWindowState {
            selected_result: String,
        }

        let mut options = TestOptions::new();
        options.help_lang = HelpLanguage::Eng;
        options.reload_help().unwrap();
        let state = CoefficientsWindowState {
            selected_result: "fit-17".to_string(),
        };
        let mut harness = Harness::new_ui_state(
            |ui, _state: &mut CoefficientsWindowState| {
                contextual_help_link(ui, "Coefficients Handling")
            },
            state,
        );

        harness.get_by_label("? Help").click();
        harness.run();
        options.open_requested_contextual_help(&harness.ctx);

        assert_eq!(harness.state().selected_result, "fit-17");
        assert!(options.show_help_window);
        let section = options
            .help_selected_section
            .and_then(|index| options.parsed_help.sections.get(index))
            .expect("coefficients article should be selected");
        assert!(section.title.contains("Coefficients Handling"));
        assert!(options.parsed_help.raw_markdown.contains("same coefficient and stage"));
        assert!(options
            .parsed_help
            .raw_markdown
            .contains("Show archived Arrhenius plot"));
        assert!(options
            .parsed_help
            .raw_markdown
            .contains("Publish fitted rate column"));
    }

    #[test]
    fn column_manager_help_link_keeps_inspector_selection_and_opens_its_article() {
        #[derive(Default)]
        struct ManagerState {
            selected_column: String,
        }

        let mut options = TestOptions::new();
        options.help_lang = HelpLanguage::Rus;
        options.reload_help().unwrap();
        let state = ManagerState {
            selected_column: "sg_mass".to_string(),
        };
        let mut harness = Harness::new_ui_state(
            |ui, _state: &mut ManagerState| contextual_help_link(ui, "Column Manager"),
            state,
        );

        harness.get_by_label("? Help").click();
        harness.run();
        options.open_requested_contextual_help(&harness.ctx);

        assert_eq!(harness.state().selected_column, "sg_mass");
        assert!(options.show_help_window);
        assert_eq!(options.help_lang, HelpLanguage::Rus);
        let section = options
            .help_selected_section
            .and_then(|index| options.parsed_help.sections.get(index))
            .expect("Column Manager article should be selected");
        assert!(section.title.contains("Column Manager"));
    }

    #[test]
    fn help_close_button_closes_the_window() {
        let mut options = TestOptions::new();
        options.reload_help().unwrap();
        options.show_help_window = true;
        let mut harness = Harness::new_ui_state(
            |ui, options: &mut TestOptions| options.show_help_window_ui(ui.ctx()),
            options,
        );

        harness.get_by_label("Close").click();
        harness.run();

        assert!(!harness.state().show_help_window);
    }

    #[test]
    fn help_cancel_discards_editor_changes_and_returns_to_browser() {
        let mut options = TestOptions::new();
        options.reload_help().unwrap();
        options.show_help_window = true;
        options.help_edit_mode = true;
        options.help_editor_buffer.push_str("\nunsaved edit");
        let original = options.parsed_help.raw_markdown.clone();
        let mut harness = Harness::new_ui_state(
            |ui, options: &mut TestOptions| options.show_help_window_ui(ui.ctx()),
            options,
        );

        harness.get_by_label("Cancel").click();
        harness.run();

        assert!(!harness.state().help_edit_mode);
        assert_eq!(harness.state().help_editor_buffer, original);
        assert!(harness.state().show_help_window);
    }
}