mdmodels 0.2.10

A tool to generate models, code and schemas from markdown files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
/*
 * Copyright (c) 2025 Jan Range
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */

use colored::Colorize;
use convert_case::{Case, Casing};
use core::panic;
use lazy_static::lazy_static;
use log::error;
use std::collections::{BTreeMap, HashMap};
use std::error::Error;
use std::path::Path;

use pulldown_cmark::{CowStr, Event, HeadingLevel, OffsetIter, Options, Parser, Tag, TagEnd};
use regex::Regex;

use crate::attribute;
use crate::datamodel::DataModel;
use crate::object::{self, Enumeration, Object};
use crate::option::RawOption;
use crate::validation::Validator;

use super::frontmatter::{parse_frontmatter, FrontMatter, ImportType};
use super::position::{Position, PositionRange};

lazy_static! {
    static ref MD_MODEL_TYPES: BTreeMap<&'static str, &'static str> = {
        let mut m = BTreeMap::new();
        m.insert(
            "Equation",
            include_str!("../../types/equation/equation-internal.json"),
        );
        m.insert(
            "UnitDefinition",
            include_str!("../../types/unit-definition/unit-definition-internal.json"),
        );
        m
    };
}

// Heading levels for re-use
const H1: Tag = Tag::Heading {
    level: HeadingLevel::H1,
    id: None,
    classes: Vec::new(),
    attrs: Vec::new(),
};
const H2: Tag = Tag::Heading {
    level: HeadingLevel::H2,
    id: None,
    classes: Vec::new(),
    attrs: Vec::new(),
};
const H3: Tag = Tag::Heading {
    level: HeadingLevel::H3,
    id: None,
    classes: Vec::new(),
    attrs: Vec::new(),
};

const H3_END: TagEnd = TagEnd::Heading(HeadingLevel::H3);

#[derive(Debug, PartialEq, Eq)]
enum ParserState {
    InDefinition,
    OutsideDefinition,
    InHeading,
}

/// Parses a Markdown file and returns a DataModel.
///
/// # Arguments
/// * `content` - The markdown content to parse
/// * `path` - Optional path to the markdown file
///
/// # Returns
/// * `Result<DataModel, Validator>` - The parsed data model or validation errors
#[allow(clippy::result_large_err)]
pub fn parse_markdown(content: &str, path: Option<&Path>) -> Result<DataModel, Validator> {
    let content = clean_content(content);
    let config = parse_frontmatter(&content).unwrap_or_default();
    let line_offsets = create_line_offsets(&content);

    let mut model = DataModel::new(None, Some(config.clone()));
    let (objects, enums) = parse_model_components(&content, &line_offsets, &mut model);

    process_model_components(&mut model, objects, enums, &config);
    merge_imports(&mut model, config.imports, path);

    validate_model(&model)?;
    Ok(model)
}

/// Creates a vector of line offset positions from content.
///
/// # Arguments
/// * `content` - The content to analyze
///
/// # Returns
/// * Vector of line offset positions
fn create_line_offsets(content: &str) -> Vec<usize> {
    content
        .char_indices()
        .filter(|(_, c)| *c == '\n')
        .map(|(i, _)| i)
        .collect()
}

/// Parses objects and enums from the markdown content.
///
/// # Arguments
/// * `content` - The markdown content to parse
/// * `line_offsets` - Vector of line offset positions
/// * `model` - Mutable reference to the data model
///
/// # Returns
/// * Tuple containing vectors of objects and enums
fn parse_model_components(
    content: &str,
    line_offsets: &[usize],
    model: &mut DataModel,
) -> (Vec<Object>, Vec<Enumeration>) {
    let mut objects = Vec::new();
    let mut enums = Vec::new();

    // Parse objects
    let mut options = Options::empty();
    options.insert(Options::ENABLE_HEADING_ATTRIBUTES);
    let mut iterator = Parser::new_ext(content, options).into_offset_iter();
    let mut state = ParserState::OutsideDefinition;

    while let Some(event) = iterator.next() {
        process_object_event(
            content,
            &mut iterator,
            &mut objects,
            event,
            model,
            &mut state,
            line_offsets,
        );
    }

    // Parse enums
    let mut iterator = Parser::new(content).into_offset_iter();
    while let Some((event, range)) = iterator.next() {
        process_enum_event(
            content,
            &mut iterator,
            &mut enums,
            (event, range),
            line_offsets,
        );
    }

    (objects, enums)
}

/// Processes and filters model components, applying inheritance and internal types.
///
/// # Arguments
/// * `model` - Mutable reference to the data model
/// * `objects` - Vector of parsed objects
/// * `enums` - Vector of parsed enums
/// * `config` - Reference to the configuration
fn process_model_components(
    model: &mut DataModel,
    objects: Vec<Object>,
    enums: Vec<Enumeration>,
    config: &FrontMatter,
) {
    let allow_empty = &config.allow_empty;

    // Filter and set components
    model.enums = enums.into_iter().filter(|e| e.has_values()).collect();
    model.objects = objects
        .into_iter()
        .filter(|o| {
            if *allow_empty {
                !&model.enums.iter().any(|e| e.name == o.name)
            } else {
                o.has_attributes()
            }
        })
        .collect();

    set_enum_attributes(model);
    add_internal_types(model);
    add_mixin_types(model).expect("Failed to add mixin types");
}

/// Merges imported models into the main model.
///
/// # Arguments
/// * `model` - Mutable reference to the data model
/// * `imports` - The imports configuration
/// * `path` - Optional path to the markdown file
fn merge_imports(model: &mut DataModel, imports: HashMap<String, ImportType>, path: Option<&Path>) {
    for (_prefix, import) in imports {
        let model_to_merge = import.fetch(path).unwrap();
        model.merge(&model_to_merge);
    }
}

/// Validates the model and returns any validation errors.
///
/// # Arguments
/// * `model` - Reference to the data model to validate
///
/// # Returns
/// * `Result<(), Validator>` - Ok if valid, Err with validator if invalid
#[allow(clippy::result_large_err)]
pub(crate) fn validate_model(model: &DataModel) -> Result<(), Validator> {
    let mut validator = Validator::new();
    validator.validate(model);

    if !validator.is_valid {
        return Err(validator);
    }
    Ok(())
}

fn clean_content(content: &str) -> String {
    // Remove all html tags
    let re = Regex::new(r"<[^>]*>").unwrap();
    let content = re.replace_all(content, "").to_string();

    // Remove all Markdown links
    let re = Regex::new(r"\[([^]]+)]\([^)]+\)").unwrap();
    let content = re.replace_all(content.as_str(), "$1").to_string();

    content
}

// Helper function to convert byte offset to line and column numbers
fn get_position(content: &str, line_offsets: &[usize], start: usize, end: usize) -> Position {
    let line = match line_offsets.binary_search(&start) {
        Ok(line) => line + 1,
        Err(line) => line + 1,
    };

    // Get the line content
    let line_start = if line > 1 { line_offsets[line - 2] } else { 0 };
    let line_end = if line <= line_offsets.len() {
        line_offsets[line - 1]
    } else {
        content.len()
    };
    let line_content = &content[line_start..line_end];

    // Count leading whitespace
    let leading_space = line_content
        .chars()
        .take_while(|c| c.is_whitespace())
        .count();

    // Calculate column numbers, adding leading whitespace to start
    let start_col = if line > 1 {
        start - line_offsets[line - 2] + leading_space - 1
    } else {
        start + 1 + leading_space
    };

    let end_col = if line <= line_offsets.len() {
        line_offsets[line - 1] - (if line > 1 { line_offsets[line - 2] } else { 0 })
    } else {
        end - (if line > 1 { line_offsets[line - 2] } else { 0 })
    };

    Position {
        line,
        column: PositionRange {
            start: start_col,
            end: end_col,
        },
        offset: PositionRange { start, end },
    }
}

/// Processes a single Markdown event for object extraction.
///
/// # Arguments
///
/// * `content` - The full content of the markdown file
/// * `iterator` - A mutable reference to the parser iterator
/// * `objects` - A mutable reference to the vector of objects
/// * `event` - The current Markdown event and its range
/// * `model` - A mutable reference to the data model
/// * `state` - A mutable reference to the parser state
/// * `line_offsets` - A reference to the line offsets of the file
fn process_object_event(
    content: &str,
    iterator: &mut pulldown_cmark::OffsetIter,
    objects: &mut Vec<Object>,
    event: (Event, std::ops::Range<usize>),
    model: &mut DataModel,
    state: &mut ParserState,
    line_offsets: &[usize],
) {
    let (event, range) = event;

    match event {
        Event::Start(tag) if tag == H1 => {
            handle_h1_event(iterator, model);
        }
        Event::Start(tag) if tag == H2 => {
            *state = ParserState::OutsideDefinition;
        }
        Event::Start(tag) if tag == H3 => {
            handle_h3_start(content, iterator, objects, state, line_offsets, range);
        }
        Event::End(tag) if tag == H3_END => {
            *state = ParserState::InDefinition;
        }
        Event::Text(CowStr::Borrowed(text)) if text.starts_with(":") => {
            handle_type_annotation(objects, text);
        }
        Event::Text(CowStr::Borrowed("[")) => {
            if *state == ParserState::InHeading {
                handle_mixin(objects, iterator);
            }
        }
        Event::Start(Tag::List(None)) => {
            if *state == ParserState::OutsideDefinition {
                return;
            }

            handle_list_start(content, iterator, objects, line_offsets, range);
        }
        Event::Start(Tag::Item) => {
            if *state == ParserState::OutsideDefinition {
                return;
            }

            handle_list_item(content, iterator, objects, line_offsets, range);
        }
        Event::Text(text) if text.to_string() == "]" => {
            handle_array_marker(objects);
        }
        Event::Text(text) if *state == ParserState::InDefinition => {
            handle_docstring(objects, text);
        }
        _ => {}
    }
}

/// Handles H1 heading events by setting the model name.
///
/// # Arguments
///
/// * `iterator` - A mutable reference to the markdown parser iterator
/// * `model` - A mutable reference to the data model to update
fn handle_h1_event(iterator: &mut pulldown_cmark::OffsetIter, model: &mut DataModel) {
    model.name = Some(extract_name(iterator));
}

/// Handles H3 heading start events by creating and adding a new object.
///
/// # Arguments
///
/// * `content` - The full content of the markdown file
/// * `iterator` - A mutable reference to the parser iterator
/// * `objects` - A mutable reference to the vector of objects
/// * `state` - A mutable reference to the parser state
/// * `line_offsets` - A reference to the line offsets of the file
/// * `range` - The byte range of the current event
fn handle_h3_start(
    content: &str,
    iterator: &mut pulldown_cmark::OffsetIter,
    objects: &mut Vec<Object>,
    state: &mut ParserState,
    line_offsets: &[usize],
    range: std::ops::Range<usize>,
) {
    *state = ParserState::InHeading;
    let mut object = process_object_heading(iterator);
    object.set_position(get_position(content, line_offsets, range.start, range.end));
    objects.push(object);
}

/// Handles type annotations in the format ": type".
///
/// # Arguments
///
/// * `objects` - A mutable slice of objects
/// * `text` - The text containing the type annotation
fn handle_type_annotation(objects: &mut [Object], text: &str) {
    let attribute = objects.last_mut().unwrap().get_last_attribute();
    if let Some(attribute) = attribute {
        attribute
            .add_option(RawOption::new(
                "type".to_string(),
                text.to_string().trim_start_matches(':').trim().to_string(),
            ))
            .unwrap();
    }
}

/// Handles inheritance declarations in object headings.
///
/// # Arguments
///
/// * `objects` - A mutable slice of objects
/// * `iterator` - A mutable reference to the parser iterator
fn handle_mixin(objects: &mut [Object], iterator: &mut pulldown_cmark::OffsetIter) {
    let last_object = objects.last_mut().unwrap();
    let mixin = iterator.next();

    match mixin {
        Some((Event::Text(text), _)) if text.to_string() != "]" => {
            last_object.mixins = text.split(',').map(|s| s.trim().to_string()).collect();
        }
        _ => {
            error!(
                "[{}] {}: Opening bracket but no mixin name. Mixin wont be applied",
                last_object.name.bold(),
                "SyntaxError".bold(),
            );
            panic!("Mixin syntax error. Expected mixin name after opening bracket.");
        }
    }
}

/// Handles the start of a list, processing either attributes or attribute options.
///
/// # Arguments
///
/// * `content` - The full content of the markdown file
/// * `iterator` - A mutable reference to the parser iterator
/// * `objects` - A mutable reference to the vector of objects
/// * `line_offsets` - A reference to the line offsets of the file
/// * `range` - The byte range of the current event
fn handle_list_start(
    content: &str,
    iterator: &mut pulldown_cmark::OffsetIter,
    objects: &mut [Object],
    line_offsets: &[usize],
    range: std::ops::Range<usize>,
) {
    let last_object = objects.last_mut().unwrap();
    if !last_object.has_attributes() {
        iterator.next();
        let (required, attr_name, dtypes) = extract_attr_name_required(iterator);
        let mut attribute = attribute::Attribute::new(attr_name, required);

        if let Some((key, dtypes)) = dtypes {
            attribute.add_option(RawOption::new(key, dtypes)).unwrap();
        }

        attribute.set_position(get_position(content, line_offsets, range.start, range.end));
        objects.last_mut().unwrap().add_attribute(attribute);
    } else {
        let attr_strings = extract_attribute_options(iterator);
        for attr_string in attr_strings {
            distribute_attribute_options(objects, attr_string);
        }
    }
}

/// Handles list items by creating new attributes.
///
/// # Arguments
///
/// * `content` - The full content of the markdown file
/// * `iterator` - A mutable reference to the parser iterator
/// * `objects` - A mutable reference to the vector of objects
/// * `line_offsets` - A reference to the line offsets of the file
/// * `range` - The byte range of the current event
fn handle_list_item(
    content: &str,
    iterator: &mut pulldown_cmark::OffsetIter,
    objects: &mut [Object],
    line_offsets: &[usize],
    range: std::ops::Range<usize>,
) {
    let (required, attr_string, dtypes) = extract_attr_name_required(iterator);
    let mut attribute = attribute::Attribute::new(attr_string, required);

    if let Some((key, dtypes)) = dtypes {
        attribute.add_option(RawOption::new(key, dtypes)).unwrap();
    }

    attribute.set_position(get_position(content, line_offsets, range.start, range.end));
    objects.last_mut().unwrap().add_attribute(attribute);
}

/// Handles array markers by setting the is_array flag on the last attribute.
///
/// # Arguments
///
/// * `objects` - A mutable slice of objects
fn handle_array_marker(objects: &mut [Object]) {
    let last_object = objects.last_mut().unwrap();
    let last_attribute = last_object.get_last_attribute();
    if let Some(attribute) = last_attribute {
        attribute.is_array = true;
    }
}

/// Handles docstring text by appending it to the last object's docstring.
///
/// # Arguments
///
/// * `objects` - A mutable slice of objects
/// * `text` - The text to append to the docstring
fn handle_docstring(objects: &mut [Object], text: CowStr) {
    let last_object = objects.last_mut().unwrap();
    if !last_object.docstring.is_empty() {
        last_object
            .docstring
            .push_str(format!(" {}", text.as_ref()).as_str());
    } else {
        last_object.docstring = text.as_ref().to_string();
    }

    // Remove all spaces > 1
    last_object.docstring = last_object
        .docstring
        .split_whitespace()
        .map(|s| s.trim())
        .collect::<Vec<&str>>()
        .join(" ");
}

/// Processes the heading of an object.
///
/// # Arguments
///
/// * `iterator` - A mutable reference to the parser iterator.
///
/// # Returns
///
/// An `Object` created from the heading.
fn process_object_heading(iterator: &mut OffsetIter) -> object::Object {
    let heading = extract_name(iterator);
    let (cleaned_name, term) = extract_object_term(&heading);
    // Use the cleaned name (Object::new will convert it to PascalCase)
    object::Object::new(cleaned_name, term)
}

/// Extracts the name from the next text event in the iterator.
///
/// # Arguments
///
/// * `iterator` - A mutable reference to the parser iterator.
///
/// # Returns
///
/// A string containing the extracted name.
fn extract_name(iterator: &mut OffsetIter) -> String {
    if let Some((Event::Text(text), _)) = iterator.next() {
        return text.to_string();
    }

    // Try for two text events
    for _ in 0..2 {
        if let Some((Event::Text(text), _)) = iterator.next() {
            return text.to_string();
        }
    }

    panic!("Could not extract name: Got {:?}", iterator.next().unwrap());
}

/// Extracts the attribute name and its required status from the iterator.
///
/// # Arguments
///
/// * `iterator` - A mutable reference to the parser iterator.
///
/// # Returns
///
/// A tuple containing a boolean indicating if the attribute is required and the attribute name.
fn extract_attr_name_required(
    iterator: &mut OffsetIter,
) -> (bool, String, Option<(String, String)>) {
    let mut next = iterator.next();

    // If there are newlines between the attributes, the likely a paragraph
    // is being started. We need to consume the paragraph and the following
    // text event.
    if let Some((Event::Start(Tag::Paragraph), _)) = next {
        next = iterator.next();
    }

    match next {
        Some((Event::Text(text), _)) => {
            if let Some((key, dtypes)) = shorthand_type(&text) {
                return (false, key, Some(dtypes));
            } else {
                return (false, text.to_string(), None);
            }
        }
        Some((Event::Start(Tag::Strong), _)) => {
            let next = iterator.next();
            let mut name = String::new();
            if let Some((Event::Text(text), _)) = next {
                name = text.to_string();
            }

            // Consume the Strong end tag
            iterator.next();

            return (true, name, None);
        }
        _ => {}
    }

    panic!("Could not extract attribute name. Please check the markdown file.");
}

/// Extracts a type definition from shorthand notation in the form "key: type".
///
/// # Arguments
///
/// * `text` - A string slice containing the potential shorthand type definition
///
/// # Returns
///
/// An `Option` containing a tuple of `(key, type)` strings if the text matches the shorthand format,
/// or `None` if it does not contain a colon separator.
fn shorthand_type(text: &str) -> Option<(String, (String, String))> {
    if let Some((key, dtypes)) = text.split_once(":") {
        Some((
            key.trim().to_string(),
            ("type".to_string(), dtypes.trim().to_string()),
        ))
    } else {
        None
    }
}

/// Extracts the term and cleaned name from an object heading.
///
/// # Arguments
///
/// * `heading` - A string slice containing the heading.
///
/// # Returns
///
/// A tuple containing:
/// - First element: cleaned name (heading with parentheses removed and trailing whitespace trimmed)
/// - Second element: optional term extracted from inside parentheses
fn extract_object_term(heading: &str) -> (String, Option<String>) {
    // Find the last occurrence of parentheses to handle nested cases
    if let Some(start) = heading.rfind('(') {
        if let Some(end) = heading[start..].find(')') {
            let term = heading[start + 1..start + end].to_string();
            let cleaned_name = heading[..start].trim_end().to_string();
            return (cleaned_name, Some(term));
        }
    }

    // No parentheses found, return the heading trimmed
    (heading.trim_end().to_string(), None)
}

/// Extracts attribute options from the iterator.
///
/// # Arguments
///
/// * `iterator` - A mutable reference to the parser iterator.
///
/// # Returns
///
/// A vector of strings containing the extracted attribute options.
fn extract_attribute_options(iterator: &mut OffsetIter) -> Vec<String> {
    let mut options = Vec::new();
    while let Some((next, _)) = iterator.next() {
        match next {
            Event::Start(Tag::Item) => {
                let name = extract_name(iterator);
                options.push(name);
            }
            Event::End(TagEnd::List(false)) => {
                break;
            }
            Event::Text(text) if text.to_string() == "[" => {
                let last_option = options.last_mut().unwrap();
                let lower = last_option.to_lowercase();
                if lower.contains("pattern:") || lower.contains("regex:") {
                    *last_option = format!("{last_option}[");
                } else {
                    *last_option = format!("{}[]", last_option.trim());
                }
            }
            Event::Text(text) if text.to_string() == "]" => {
                let last_option = options.last_mut().unwrap();
                let lower = last_option.to_lowercase();
                if lower.contains("pattern:") || lower.contains("regex:") {
                    *last_option = format!("{last_option}]");
                }
            }
            Event::Text(text) if text.to_string() != "]" => {
                let last_option = options.last_mut().unwrap();
                let lower = last_option.to_lowercase();
                if lower.contains("description:") {
                    *last_option = format!("{} {}", last_option.trim(), text);
                } else if lower.contains("pattern:") || lower.contains("regex:") {
                    *last_option = format!("{}{}", last_option.trim(), text);
                }
            }
            _ => {}
        }
    }
    options
}

/// Adds an option to the last attribute of the last object in the list.
///
/// # Arguments
///
/// * `objects` - A mutable reference to the list of objects.
/// * `key` - The key of the attribute option.
/// * `value` - The value of the attribute option.
fn add_option_to_last_attribute(
    objects: &mut [object::Object],
    key: String,
    value: String,
) -> Result<(), Box<dyn Error>> {
    let last_attr = objects.last_mut().unwrap().get_last_attribute();
    if let Some(attribute) = last_attr {
        let option = RawOption::new(key, value);
        attribute.add_option(option)?;
    }

    Ok(())
}

/// Distributes attribute options among the objects.
///
/// # Arguments
///
/// * `objects` - A mutable reference to the list of objects.
/// * `attr_string` - A string containing the attribute or option.
///
/// # Returns
///
/// An optional unit type.
fn distribute_attribute_options(objects: &mut [object::Object], attr_string: String) -> Option<()> {
    if attr_string.contains(':') {
        let (key, value) = process_option(&attr_string);
        add_option_to_last_attribute(objects, key, value).expect("Failed to add option");
        return None;
    }

    objects
        .last_mut()
        .unwrap()
        .create_new_attribute(attr_string, false);

    None
}

/// Processes an attribute option string.
///
/// # Arguments
///
/// * `option` - A string containing the attribute option.
///
/// # Returns
///
/// A tuple containing the key and value of the attribute option.
fn process_option(option: &String) -> (String, String) {
    let parts: Vec<&str> = option.split(':').collect();

    assert!(
        parts.len() > 1,
        "Attribute {option} does not have a valid option"
    );

    let key = parts[0].trim();
    let value = parts[1..].join(":");

    (key.to_string(), value.trim().to_string())
}

/// Processes a single Markdown event for enumeration extraction.
///
/// # Arguments
///
/// * `iterator` - A mutable reference to the parser iterator.
/// * `enums` - A mutable reference to the vector of enumerations.
/// * `event` - The current Markdown event.
/// * `range` - The range of the event.
/// * `line_offsets` - The line offsets of the file.
pub fn process_enum_event(
    content: &str,
    iterator: &mut OffsetIter,
    enums: &mut Vec<Enumeration>,
    event: (Event, std::ops::Range<usize>),
    line_offsets: &[usize],
) {
    let (event, range) = event;

    match event {
        Event::Start(tag) if tag == H3 => {
            let enum_name = extract_name(iterator);
            let mut enum_obj = Enumeration {
                name: enum_name.replace(" ", "_").to_case(Case::Pascal),
                mappings: BTreeMap::new(),
                docstring: "".to_string(),
                position: None,
            };
            enum_obj.set_position(get_position(content, line_offsets, range.start, range.end));
            enums.push(enum_obj);
        }
        Event::Start(Tag::CodeBlock(pulldown_cmark::CodeBlockKind::Fenced(_))) => {
            let event = iterator.next().unwrap();
            if let (Event::Text(text), _) = event {
                let mappings = text.to_string();

                if enums.last_mut().is_some() {
                    let enum_obj = enums.last_mut().unwrap();
                    process_enum_mappings(enum_obj, mappings);
                }
            }
        }
        _ => {}
    }
}

/// Processes enumeration mappings from a code block.
///
/// # Arguments
///
/// * `enum_obj` - A mutable reference to the enumeration object.
/// * `mappings` - A string containing the mappings.
fn process_enum_mappings(enum_obj: &mut Enumeration, mappings: String) {
    let lines = mappings.split('\n');
    for line in lines {
        let parts: Vec<&str> = line.split('=').collect();
        if parts.len() != 2 {
            // Skip empty lines or lines that do not contain a mapping
            continue;
        }

        // Extract key and value, insert into enum object
        let key = parts[0].trim().replace('"', "");
        let value = parts[1].trim().replace('"', "");
        enum_obj.mappings.insert(key.to_string(), value.to_string());
    }
}

/// Adds mixin types to the objects in the model.
///
/// This function processes mixins by adding attributes from mixin objects to their children.
/// It handles both user-defined mixins and internal type mixins.
///
/// # Arguments
///
/// * `model` - A mutable reference to the data model.
///
/// # Returns
///
/// * `Result<(), Box<dyn Error>>` - Ok if successful, or an error if mixin fails.
///
/// # Panics
///
/// Panics if an object has a mixin that does not exist.
///
/// # Errors
///
/// An error is logged if an object has a mixin that does not exist.
///
fn add_mixin_types(model: &mut DataModel) -> Result<(), Box<dyn Error>> {
    // Filter and clone the objects without a mixin
    let mixins = collect_mixin_objects(model);

    let mut to_merge = Vec::new();
    let mut added_internals = Vec::new();

    // Process each object that has a mixin
    for object in model.objects.iter_mut() {
        for local_mixin in object.mixins.clone() {
            process_mixins(
                object,
                &local_mixin,
                &mixins,
                &mut to_merge,
                &mut added_internals,
            )?;
        }
    }

    // Merge all collected internal types
    merge_internal_types(model, to_merge);

    Ok(())
}

/// Collects all objects that can serve as mixins (those without mixins themselves)
///
/// # Arguments
///
/// * `model` - A reference to the data model.
///
/// # Returns
///
/// * `Vec<Object>` - A vector of objects that can be used as mixins.
fn collect_mixin_objects(model: &DataModel) -> Vec<Object> {
    model
        .objects
        .iter()
        .filter(|o| o.mixins.is_empty())
        .cloned()
        .collect()
}

/// Processes mixin for a single object
///
/// This function handles the mixin logic for a specific object by finding its mixin
/// and extending the object's attributes with those from the mixin.
///
/// # Arguments
///
/// * `object` - A mutable reference to the object being processed.
/// * `mixin_name` - The name of the mixin object.
/// * `mixins` - A slice of available mixin objects.
/// * `to_merge` - A mutable reference to a vector of data models to be merged.
/// * `added_internals` - A mutable reference to a vector of internal type names that have been added.
///
/// # Returns
///
/// * `Result<(), Box<dyn Error>>` - Ok if successful, or an error if the mixin is not found.
fn process_mixins(
    object: &mut Object,
    mixin_name: &str,
    mixins: &[Object],
    to_merge: &mut Vec<DataModel>,
    added_internals: &mut Vec<String>,
) -> Result<(), Box<dyn Error>> {
    if let Some(mixin) = find_mixin_in_objects(mixin_name, mixins) {
        // Mixin found in existing objects
        object.attributes.extend(mixin.attributes.clone());
    } else if let Some(internal_type) = MD_MODEL_TYPES.get(mixin_name) {
        // Mixin is an internal type
        process_internal_mixin_type(object, mixin_name, internal_type, to_merge, added_internals);
    } else {
        // Mixin not found
        return report_missing_mixin(object, mixin_name);
    }

    Ok(())
}

/// Finds a mixin object by name in the list of available mixins
///
/// # Arguments
///
/// * `mixin_name` - The name of the mixin object to find.
/// * `mixins` - A slice of available mixin objects.
///
/// # Returns
///
/// * `Option<&'a Object>` - A reference to the mixin object if found, or None if not found.
fn find_mixin_in_objects<'a>(mixin_name: &str, mixins: &'a [Object]) -> Option<&'a Object> {
    mixins.iter().find(|o| o.name == mixin_name)
}

/// Processes an internal mixin type
///
/// This function handles inheritance from internal predefined types by extracting
/// attributes from the internal type and adding them to the object.
///
/// # Arguments
///
/// * `object` - A mutable reference to the object being processed.
/// * `mixin_name` - The name of the internal mixin type.
/// * `internal_type_json` - The JSON string representation of the internal type.
/// * `to_merge` - A mutable reference to a vector of data models to be merged.
/// * `added_internals` - A mutable reference to a vector of internal type names that have been added.
fn process_internal_mixin_type(
    object: &mut Object,
    mixin_name: &str,
    internal_type_json: &str,
    to_merge: &mut Vec<DataModel>,
    added_internals: &mut Vec<String>,
) {
    let mut internal_type = serde_json::from_str::<DataModel>(internal_type_json)
        .expect("Failed to parse internal data type");

    // Pop the first object mixin and add the attributes
    let target_obj = internal_type.objects[0].clone();
    internal_type.objects.remove(0);

    object.attributes.extend(target_obj.attributes.clone());

    if !added_internals.contains(&mixin_name.to_string()) {
        to_merge.push(internal_type);
        added_internals.push(mixin_name.to_string());
    }
}

/// Reports a missing mixin error
///
/// # Arguments
///
/// * `object` - A reference to the object with the missing mixin.
/// * `mixin_name` - The name of the mixin that was not found.
///
/// # Returns
///
/// * `Result<(), Box<dyn Error>>` - An error indicating the mixin does not exist.
fn report_missing_mixin(object: &Object, mixin_name: &str) -> Result<(), Box<dyn Error>> {
    error!(
        "[{}] {}: Mixin {} does not exist.",
        object.name.red().bold(),
        "InheritanceError".bold(),
        mixin_name.red().bold(),
    );

    Err("Object has a mixin that does not exist".into())
}

/// Merges all collected internal types into the model
///
/// # Arguments
///
/// * `model` - A mutable reference to the data model.
/// * `to_merge` - A vector of data models to be merged into the main model.
fn merge_internal_types(model: &mut DataModel, to_merge: Vec<DataModel>) {
    for internal in to_merge {
        model.merge(&internal);
    }
}

/// Adds internal types to the model based on attribute data types
///
/// This function identifies internal types that are referenced in object attributes
/// and adds them to the model if they're not already present.
///
/// # Arguments
///
/// * `model` - A mutable reference to the data model.
fn add_internal_types(model: &mut DataModel) {
    // Get all datatypes within the model
    let mut all_types = vec![];
    for object in &model.objects {
        for attr in &object.attributes {
            all_types.extend(attr.dtypes.clone());
        }
    }

    let object_names = model
        .objects
        .iter()
        .map(|obj| obj.name.clone())
        .collect::<Vec<String>>();

    for (name, content) in MD_MODEL_TYPES.iter() {
        if object_names.contains(&name.to_string()) {
            continue;
        }

        if all_types.contains(&name.to_string()) {
            model.merge(
                &serde_json::from_str::<DataModel>(content)
                    .expect("Failed to parse internal data type"),
            )
        }
    }
}

/// Sets the `is_enum` flag for attributes that are enumerations.
///
/// This function iterates through all objects and their attributes in the data model.
/// If an attribute's data types match any of the enumeration names, the `is_enum` flag
/// is set to `true`. If an attribute has data types that do not match any enumeration,
/// an error is returned.
///
/// # Arguments
///
/// * `model` - A mutable reference to the data model.
fn set_enum_attributes(model: &mut DataModel) {
    let enums = model
        .enums
        .iter()
        .map(|e| e.name.clone())
        .collect::<Vec<String>>();

    for object in model.objects.iter_mut() {
        for attr in object.attributes.iter_mut() {
            let enum_dtypes: Vec<String> = attr
                .dtypes
                .iter()
                .filter(|dtype| enums.contains(dtype))
                .cloned()
                .collect();
            if !enum_dtypes.is_empty() && enum_dtypes.len() == attr.dtypes.len() {
                attr.is_enum = true;
            }
        }
    }
}

/// Represents the different keys that can be used for attribute options.
pub(crate) enum OptionKey {
    /// Represents the data type of the attribute.
    Type,
    /// Represents the term associated with the attribute.
    Term,
    /// Represents the description of the attribute.
    Description,
    /// Represents the XML type information for the attribute.
    Xml,
    /// Represents the default value for the attribute.
    Default,
    /// Indicates if the attribute can have multiple values.
    Multiple,
    /// Represents any other option not covered by the predefined keys.
    Other,
}

impl OptionKey {
    /// Converts a string to an `OptionKey`.
    ///
    /// # Arguments
    ///
    /// * `key` - The string representation of the key.
    ///
    /// # Returns
    ///
    /// An `OptionKey` corresponding to the given string.
    pub fn from_str(key: &str) -> Self {
        match key.to_lowercase().as_str() {
            "type" => OptionKey::Type,
            "term" => OptionKey::Term,
            "description" => OptionKey::Description,
            "xml" => OptionKey::Xml,
            "default" => OptionKey::Default,
            "multiple" => OptionKey::Multiple,
            _ => OptionKey::Other,
        }
    }
}