cmtraceopen-parser 0.1.1

Parse ConfigMgr/SCCM, Intune, CBS, DISM, Panther, MSI, and PSADT logs with format auto-detection, severity classification, and Windows error-code lookup. Pure Rust, no I/O, native + wasm32.
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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
//! MSI verbose log parser.
//!
//! Parses Windows Installer verbose log output generated by `msiexec /l*v`.
//!
//! Recognized line patterns:
//! - Engine messages: `MSI (c) (PID:TID) [HH:MM:SS:mmm]: message`
//! - Header/footer: `=== Verbose logging started/stopped: ... ===`
//! - Action start/ended/top-level: `Action start HH:MM:SS: ActionName.`
//! - Property dumps: `Property(C): Name = Value`
//! - MainEngineThread return: `MainEngineThread is returning NNNN`
//! - Plain text fallback for unrecognized lines

use chrono::{Datelike, NaiveDate, Timelike};
use regex::Regex;

use super::severity::detect_severity_from_text;
use crate::models::log_entry::{LogEntry, LogFormat, Severity};
use std::sync::OnceLock;

// ---------------------------------------------------------------------------
// Compiled regexes
// ---------------------------------------------------------------------------

/// Engine message: MSI (c) (8C:98) [07:42:28:452]: message text
fn engine_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r"^MSI\s+\(([csaN])\)\s+\(([0-9A-Fa-f]+):([0-9A-Fa-f]+)\)\s+\[(\d{2}):(\d{2}):(\d{2}):(\d{3})\]:\s+(.*)$",
    )
    .expect("MSI engine regex must compile")
})
}

/// Header: === Verbose logging started: M/D/YYYY  H:MM:SS  Build type: ... ===
fn header_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r"^===\s+(?:Verbose\s+)?[Ll]ogging\s+started:\s+(\d{1,2}/\d{1,2}/\d{4})\s+(\d{1,2}:\d{2}:\d{2})\s+(.*)===\s*$",
    )
    .expect("MSI header regex must compile")
})
}

/// Footer: === Verbose logging stopped: ... ===
fn footer_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r"^===\s+(?:Verbose\s+)?[Ll]ogging\s+stopped:\s+.*===\s*$")
            .expect("MSI footer regex must compile")
    })
}

/// Action start: Action start 16:34:29: InstallFiles.
fn action_start_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r"^Action start (\d{1,2}):(\d{2}):(\d{2}):\s+(\w+)\.\s*$")
            .expect("MSI action start regex must compile")
    })
}

/// Action ended: Action ended 16:34:29: InstallFiles. Return value 1.
fn action_ended_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r"^Action ended (\d{1,2}):(\d{2}):(\d{2}):\s+(\w+)\.\s+Return value (\d+)\.\s*$")
            .expect("MSI action ended regex must compile")
    })
}

/// Top-level action: Action 16:34:29: INSTALL.
fn action_top_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r"^Action (\d{1,2}):(\d{2}):(\d{2}):\s+(\w+)\.\s*$")
            .expect("MSI top-level action regex must compile")
    })
}

/// Property dump: Property(C): ProductCode = {GUID}
fn property_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r"^Property\([CScs]\):\s+(.*)$").expect("MSI property regex must compile")
    })
}

/// MainEngineThread return: MainEngineThread is returning 1603
fn main_engine_return_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r"^MainEngineThread is returning (\d+)")
            .expect("MSI MainEngineThread regex must compile")
    })
}

/// Note error code pattern: Note: 1: NNNN
fn note_error_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r"Note:\s+1:\s+(\d+)").expect("MSI note error regex must compile")
    })
}

// ---------------------------------------------------------------------------
// Detection helper (used by detect.rs)
// ---------------------------------------------------------------------------

/// Returns a weight indicating how likely this line is from an MSI verbose log.
/// Higher weight = stronger signal.
pub fn matches_msi_content(line: &str) -> u32 {
    let trimmed = line.trim();

    if trimmed.starts_with("=== Verbose logging started:")
        || trimmed.starts_with("=== Logging started:")
        || trimmed.starts_with("=== verbose logging started:")
        || trimmed.starts_with("=== logging started:")
    {
        return 3;
    }

    if trimmed.starts_with("MSI (c)")
        || trimmed.starts_with("MSI (s)")
        || trimmed.starts_with("MSI (a)")
        || trimmed.starts_with("MSI (N)")
    {
        return 2;
    }

    if trimmed.starts_with("MainEngineThread is returning") {
        return 2;
    }

    if action_start_re().is_match(trimmed) || action_ended_re().is_match(trimmed) {
        return 1;
    }

    if trimmed.starts_with("Property(S):") || trimmed.starts_with("Property(C):") {
        return 1;
    }

    0
}

// ---------------------------------------------------------------------------
// Parser state
// ---------------------------------------------------------------------------

/// Mutable state carried across lines during parsing.
struct MsiParserState {
    /// Date extracted from the header line, applied to subsequent time-only entries.
    current_date: Option<NaiveDate>,
    /// Previous time-of-day in seconds, used for midnight rollover detection.
    prev_time_secs: Option<u32>,
}

impl MsiParserState {
    fn new() -> Self {
        Self {
            current_date: None,
            prev_time_secs: None,
        }
    }

    /// Update date state, detecting midnight rollover.
    /// Returns the date to use for this entry's timestamp.
    fn advance_time(&mut self, h: u32, m: u32, s: u32) -> Option<NaiveDate> {
        let current_secs = h * 3600 + m * 60 + s;

        if let Some(prev_secs) = self.prev_time_secs {
            // If time jumped back by more than 23 hours, assume midnight rollover
            if current_secs < prev_secs && (prev_secs - current_secs) > 82800 {
                if let Some(date) = self.current_date {
                    self.current_date = date.succ_opt();
                }
            }
        }
        self.prev_time_secs = Some(current_secs);

        self.current_date
    }
}

// ---------------------------------------------------------------------------
// Public parse entry point
// ---------------------------------------------------------------------------

/// Parse all lines as MSI verbose log format.
pub fn parse_lines(lines: &[&str], file_path: &str) -> (Vec<LogEntry>, u32) {
    let mut entries = Vec::with_capacity(lines.len());
    let mut errors = 0u32;
    let mut id_counter = 0u64;
    let mut state = MsiParserState::new();

    for (i, line) in lines.iter().enumerate() {
        if line.trim().is_empty() {
            continue;
        }

        let entry = parse_msi_line(line, file_path, &mut state, id_counter, (i + 1) as u32);
        let is_fallback = entry.component.is_none()
            && entry.timestamp.is_none()
            && !footer_re().is_match(line.trim());

        entries.push(entry);

        if is_fallback {
            errors += 1;
        }

        id_counter += 1;
    }

    (entries, errors)
}

// ---------------------------------------------------------------------------
// Line-level parsing
// ---------------------------------------------------------------------------

fn parse_msi_line(
    line: &str,
    file_path: &str,
    state: &mut MsiParserState,
    id: u64,
    line_number: u32,
) -> LogEntry {
    let trimmed = line.trim_end();

    // 1. Header line
    if let Some(caps) = header_re().captures(trimmed) {
        return parse_header(caps, file_path, state, id, line_number, trimmed);
    }

    // 2. Footer line
    if footer_re().is_match(trimmed) {
        return make_entry(
            id,
            line_number,
            trimmed.to_string(),
            Some("MSI-header".to_string()),
            None,
            None,
            Severity::Info,
            None,
            None,
            file_path,
        );
    }

    // 3. Engine message
    if let Some(caps) = engine_re().captures(trimmed) {
        return parse_engine(caps, file_path, state, id, line_number);
    }

    // 4. Action ended (check before action start — "ended" is more specific)
    if let Some(caps) = action_ended_re().captures(trimmed) {
        return parse_action_ended(caps, file_path, state, id, line_number, trimmed);
    }

    // 5. Action start
    if let Some(caps) = action_start_re().captures(trimmed) {
        return parse_action_start(caps, file_path, state, id, line_number, trimmed);
    }

    // 6. Top-level action
    if let Some(caps) = action_top_re().captures(trimmed) {
        return parse_action_top(caps, file_path, state, id, line_number, trimmed);
    }

    // 7. Property dump
    if let Some(caps) = property_re().captures(trimmed) {
        return make_entry(
            id,
            line_number,
            caps.get(1).map_or("", |m| m.as_str()).to_string(),
            Some("MSI-properties".to_string()),
            None,
            None,
            Severity::Info,
            None,
            None,
            file_path,
        );
    }

    // 8. MainEngineThread return
    if let Some(caps) = main_engine_return_re().captures(trimmed) {
        let code: u32 = caps
            .get(1)
            .and_then(|m| m.as_str().parse().ok())
            .unwrap_or(0);
        let severity = severity_from_msi_exit_code(code);
        return make_entry(
            id,
            line_number,
            trimmed.to_string(),
            Some("MSI-engine".to_string()),
            None,
            None,
            severity,
            None,
            None,
            file_path,
        );
    }

    // 9. Fallback — plain text with keyword-based severity
    let severity = msi_text_severity(trimmed);
    make_entry(
        id,
        line_number,
        trimmed.to_string(),
        None,
        None,
        None,
        severity,
        None,
        None,
        file_path,
    )
}

// ---------------------------------------------------------------------------
// Per-pattern parsers
// ---------------------------------------------------------------------------

fn parse_header(
    caps: regex::Captures,
    file_path: &str,
    state: &mut MsiParserState,
    id: u64,
    line_number: u32,
    raw: &str,
) -> LogEntry {
    // Extract date: M/D/YYYY
    let date_str = caps.get(1).map(|m| m.as_str()).unwrap_or("");
    let time_str = caps.get(2).map(|m| m.as_str()).unwrap_or("");

    let parsed_date = parse_us_date(date_str);
    if let Some(d) = parsed_date {
        state.current_date = Some(d);
    }

    // Parse time H:MM:SS
    let time_parts: Vec<u32> = time_str.split(':').filter_map(|p| p.parse().ok()).collect();
    let (h, m, s) = if time_parts.len() == 3 {
        (time_parts[0], time_parts[1], time_parts[2])
    } else {
        (0, 0, 0)
    };

    let (timestamp, timestamp_display) = if let Some(date) = parsed_date {
        build_timestamp(date, h, m, s, 0)
    } else {
        (None, None)
    };

    if time_parts.len() == 3 {
        state.prev_time_secs = Some(h * 3600 + m * 60 + s);
    }

    make_entry(
        id,
        line_number,
        raw.to_string(),
        Some("MSI-header".to_string()),
        timestamp,
        timestamp_display,
        Severity::Info,
        None,
        None,
        file_path,
    )
}

fn parse_engine(
    caps: regex::Captures,
    file_path: &str,
    state: &mut MsiParserState,
    id: u64,
    line_number: u32,
) -> LogEntry {
    let context_char = caps.get(1).map(|m| m.as_str()).unwrap_or("c");
    let pid_hex = caps.get(2).map(|m| m.as_str()).unwrap_or("0");
    let tid_hex = caps.get(3).map(|m| m.as_str()).unwrap_or("0");
    let h: u32 = caps
        .get(4)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let m: u32 = caps
        .get(5)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let s: u32 = caps
        .get(6)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let ms: u32 = caps
        .get(7)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let message = caps.get(8).map(|m| m.as_str()).unwrap_or("").to_string();

    let component = match context_char {
        "c" => "MSI-client",
        "s" => "MSI-server",
        "a" => "MSI-action",
        "N" => "MSI-nested",
        _ => "MSI-client",
    }
    .to_string();

    let thread_num = u32::from_str_radix(tid_hex, 16).ok();
    let thread_display = Some(format!("{}:{}", pid_hex, tid_hex));

    let date = state.advance_time(h, m, s);
    let (timestamp, timestamp_display) = if let Some(d) = date {
        build_timestamp(d, h, m, s, ms)
    } else {
        (None, Some(format!("{:02}:{:02}:{:02}.{:03}", h, m, s, ms)))
    };

    // Severity: check MainEngineThread return in message, note error codes, keyword patterns
    let severity = determine_engine_severity(&message);

    make_entry(
        id,
        line_number,
        message,
        Some(component),
        timestamp,
        timestamp_display,
        severity,
        thread_num,
        thread_display,
        file_path,
    )
}

fn parse_action_start(
    caps: regex::Captures,
    file_path: &str,
    state: &mut MsiParserState,
    id: u64,
    line_number: u32,
    raw: &str,
) -> LogEntry {
    let h: u32 = caps
        .get(1)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let m: u32 = caps
        .get(2)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let s: u32 = caps
        .get(3)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let action = caps.get(4).map(|m| m.as_str()).unwrap_or("Unknown");

    let date = state.advance_time(h, m, s);
    let (timestamp, timestamp_display) = if let Some(d) = date {
        build_timestamp(d, h, m, s, 0)
    } else {
        (None, Some(format!("{:02}:{:02}:{:02}.000", h, m, s)))
    };

    make_entry(
        id,
        line_number,
        raw.to_string(),
        Some(action.to_string()),
        timestamp,
        timestamp_display,
        Severity::Info,
        None,
        None,
        file_path,
    )
}

fn parse_action_ended(
    caps: regex::Captures,
    file_path: &str,
    state: &mut MsiParserState,
    id: u64,
    line_number: u32,
    raw: &str,
) -> LogEntry {
    let h: u32 = caps
        .get(1)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let m: u32 = caps
        .get(2)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let s: u32 = caps
        .get(3)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let action = caps.get(4).map(|m| m.as_str()).unwrap_or("Unknown");
    let return_val: u32 = caps
        .get(5)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);

    let date = state.advance_time(h, m, s);
    let (timestamp, timestamp_display) = if let Some(d) = date {
        build_timestamp(d, h, m, s, 0)
    } else {
        (None, Some(format!("{:02}:{:02}:{:02}.000", h, m, s)))
    };

    let severity = severity_from_action_return(return_val);

    make_entry(
        id,
        line_number,
        raw.to_string(),
        Some(action.to_string()),
        timestamp,
        timestamp_display,
        severity,
        None,
        None,
        file_path,
    )
}

fn parse_action_top(
    caps: regex::Captures,
    file_path: &str,
    state: &mut MsiParserState,
    id: u64,
    line_number: u32,
    raw: &str,
) -> LogEntry {
    let h: u32 = caps
        .get(1)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let m: u32 = caps
        .get(2)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let s: u32 = caps
        .get(3)
        .and_then(|m| m.as_str().parse().ok())
        .unwrap_or(0);
    let action = caps.get(4).map(|m| m.as_str()).unwrap_or("Unknown");

    let date = state.advance_time(h, m, s);
    let (timestamp, timestamp_display) = if let Some(d) = date {
        build_timestamp(d, h, m, s, 0)
    } else {
        (None, Some(format!("{:02}:{:02}:{:02}.000", h, m, s)))
    };

    make_entry(
        id,
        line_number,
        raw.to_string(),
        Some(action.to_string()),
        timestamp,
        timestamp_display,
        Severity::Info,
        None,
        None,
        file_path,
    )
}

// ---------------------------------------------------------------------------
// Severity helpers
// ---------------------------------------------------------------------------

/// Determine severity for an engine message body.
/// Priority: MainEngineThread return code > note error codes > keyword patterns > text fallback.
fn determine_engine_severity(message: &str) -> Severity {
    // Check for MainEngineThread return code embedded in message
    if let Some(caps) = main_engine_return_re().captures(message) {
        if let Some(code) = caps.get(1).and_then(|m| m.as_str().parse::<u32>().ok()) {
            return severity_from_msi_exit_code(code);
        }
    }

    // Check for Note: 1: NNNN error codes
    if let Some(caps) = note_error_re().captures(message) {
        if let Some(code) = caps.get(1).and_then(|m| m.as_str().parse::<u32>().ok()) {
            // Common MSI note error codes that indicate real problems
            if matches!(
                code,
                2318 | 2329
                    | 2331
                    | 2335
                    | 2337
                    | 2343
                    | 2345
                    | 2350
                    | 2351
                    | 2352
                    | 2355
                    | 2356
                    | 2357
                    | 2358
                    | 2359
                    | 2360
                    | 2361
                    | 2362
                    | 2371
                    | 2372
                    | 2373
                    | 2374
                    | 2375
                    | 2379
                    | 2380
                    | 2381
                    | 2382
            ) {
                return Severity::Error;
            }
            // Most "Note: 1:" entries are informational in MSI logs
            return Severity::Info;
        }
    }

    // Keyword patterns specific to MSI logs
    let lower = message.to_lowercase();
    if lower.contains("installation failed")
        || lower.contains("error status: 1603")
        || lower.contains("error status: 1618")
        || lower.contains("product: error")
    {
        return Severity::Error;
    }

    // General text-based fallback
    detect_severity_from_text(message)
}

/// Map MSI exit/return codes to severity.
fn severity_from_msi_exit_code(code: u32) -> Severity {
    match code {
        0 => Severity::Info,       // SUCCESS
        1707 => Severity::Info,    // SUCCESS (alternate)
        3010 => Severity::Info,    // SUCCESS_REBOOT_REQUIRED
        1602 => Severity::Warning, // ERROR_INSTALL_USEREXIT
        1618 => Severity::Error,   // ERROR_INSTALL_ALREADY_RUNNING
        1603 => Severity::Error,   // ERROR_INSTALL_FAILURE
        1604 => Severity::Error,   // ERROR_INSTALL_SUSPEND
        1605 => Severity::Error,   // ERROR_UNKNOWN_PRODUCT
        1610 => Severity::Error,   // ERROR_BAD_CONFIGURATION
        1612 => Severity::Error,   // ERROR_INSTALL_SOURCE_ABSENT
        1613 => Severity::Error,   // ERROR_INSTALL_PACKAGE_VERSION
        1619 => Severity::Error,   // ERROR_INSTALL_PACKAGE_OPEN_FAILED
        1620 => Severity::Error,   // ERROR_INSTALL_PACKAGE_INVALID
        1622 => Severity::Error,   // ERROR_INSTALL_LOG_FAILURE
        1623 => Severity::Error,   // ERROR_INSTALL_LANGUAGE_UNSUPPORTED
        1624 => Severity::Error,   // ERROR_INSTALL_TRANSFORM_FAILURE
        1625 => Severity::Warning, // ERROR_INSTALL_PACKAGE_REJECTED (policy)
        1638 => Severity::Warning, // ERROR_PRODUCT_VERSION (another version installed)
        _ => {
            // Codes >= 1600 are generally MSI-specific errors
            if (1600..1700).contains(&code) {
                Severity::Error
            } else {
                Severity::Info
            }
        }
    }
}

/// Map action "Return value" to severity.
fn severity_from_action_return(code: u32) -> Severity {
    match code {
        0 => Severity::Info,    // Failure (but many logs use 0 as success)
        1 => Severity::Info,    // Success
        2 => Severity::Warning, // User cancel
        3 => Severity::Error,   // Fatal error
        4 => Severity::Warning, // Suspend
        _ => Severity::Info,
    }
}

/// MSI-specific text severity: check for known MSI patterns before general fallback.
fn msi_text_severity(text: &str) -> Severity {
    let lower = text.to_lowercase();
    if lower.contains("installation failed") || lower.contains("error status: 1603") {
        return Severity::Error;
    }
    detect_severity_from_text(text)
}

// ---------------------------------------------------------------------------
// Timestamp and date utilities
// ---------------------------------------------------------------------------

/// Parse a US-format date string: M/D/YYYY
fn parse_us_date(s: &str) -> Option<NaiveDate> {
    let parts: Vec<&str> = s.split('/').collect();
    if parts.len() != 3 {
        return None;
    }
    let month: u32 = parts[0].parse().ok()?;
    let day: u32 = parts[1].parse().ok()?;
    let year: i32 = parts[2].parse().ok()?;
    NaiveDate::from_ymd_opt(year, month, day)
}

/// Build unix-millis timestamp and display string from date + time components.
fn build_timestamp(
    date: NaiveDate,
    h: u32,
    m: u32,
    s: u32,
    ms: u32,
) -> (Option<i64>, Option<String>) {
    let dt = date.and_hms_milli_opt(h, m, s, ms);
    let timestamp = dt.map(|ndt| ndt.and_utc().timestamp_millis());
    let display = dt.map(|ndt| {
        format!(
            "{:02}-{:02}-{:04} {:02}:{:02}:{:02}.{:03}",
            date.month(),
            date.day(),
            date.year(),
            ndt.hour(),
            ndt.minute(),
            ndt.second(),
            ms,
        )
    });
    (timestamp, display)
}

// ---------------------------------------------------------------------------
// LogEntry constructor
// ---------------------------------------------------------------------------

#[allow(clippy::too_many_arguments)]
fn make_entry(
    id: u64,
    line_number: u32,
    message: String,
    component: Option<String>,
    timestamp: Option<i64>,
    timestamp_display: Option<String>,
    severity: Severity,
    thread: Option<u32>,
    thread_display: Option<String>,
    file_path: &str,
) -> LogEntry {
    LogEntry {
        id,
        line_number,
        message,
        component,
        timestamp,
        timestamp_display,
        severity,
        thread,
        thread_display,
        source_file: None,
        format: LogFormat::Timestamped,
        file_path: file_path.to_string(),
        timezone_offset: None,
        error_code_spans: Vec::new(),
        ip_address: None,
        host_name: None,
        mac_address: None,
        result_code: None,
        gle_code: None,
        setup_phase: None,
        operation_name: None,
        http_method: None,
        uri_stem: None,
        uri_query: None,
        status_code: None,
        sub_status: None,
        time_taken_ms: None,
        client_ip: None,
        server_ip: None,
        user_agent: None,
        server_port: None,
        username: None,
        win32_status: None,
        query_name: None,
        query_type: None,
        response_code: None,
        dns_direction: None,
        dns_protocol: None,
        source_ip: None,
        dns_flags: None,
        dns_event_id: None,
        zone_name: None,
        entry_kind: None,
        whatif: None,
        section_name: None,
        section_color: None,
        iteration: None,
        tags: None,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- Detection weight tests --

    #[test]
    fn test_matches_header() {
        assert_eq!(
            matches_msi_content("=== Verbose logging started: 6/13/2023  9:02:46  Build type: SHIP UNICODE 5.00.10011.00  Calling process: ... ==="),
            3
        );
    }

    #[test]
    fn test_matches_logging_started_variant() {
        assert_eq!(
            matches_msi_content("=== Logging started: 1/2/2024  10:00:00  Build type: SHIP ==="),
            3
        );
    }

    #[test]
    fn test_matches_engine_client() {
        assert_eq!(
            matches_msi_content("MSI (c) (8C:98) [07:42:28:452]: Resetting cached policy values"),
            2
        );
    }

    #[test]
    fn test_matches_engine_server() {
        assert_eq!(
            matches_msi_content("MSI (s) (8C:98) [07:42:28:452]: Running server"),
            2
        );
    }

    #[test]
    fn test_matches_main_engine_thread() {
        assert_eq!(matches_msi_content("MainEngineThread is returning 0"), 2);
    }

    #[test]
    fn test_matches_action_start() {
        assert_eq!(
            matches_msi_content("Action start 16:34:29: InstallFiles."),
            1
        );
    }

    #[test]
    fn test_matches_action_ended() {
        assert_eq!(
            matches_msi_content("Action ended 16:34:29: InstallFiles. Return value 1."),
            1
        );
    }

    #[test]
    fn test_matches_property() {
        assert_eq!(
            matches_msi_content(
                "Property(C): ProductCode = {C64CA371-0000-0000-0000-000000000000}"
            ),
            1
        );
    }

    #[test]
    fn test_matches_plain_text_zero() {
        assert_eq!(matches_msi_content("Just some random text"), 0);
    }

    // -- Header parsing --

    #[test]
    fn test_parse_header_extracts_date() {
        let lines = [
            "=== Verbose logging started: 6/13/2023  9:02:46  Build type: SHIP UNICODE 5.00.10011.00  Calling process: C:\\Windows\\System32\\msiexec.exe ===",
            "MSI (c) (8C:98) [09:02:46:452]: Resetting cached policy values",
        ];

        let (entries, errors) = parse_lines(&lines, "install.log");

        assert_eq!(errors, 0);
        assert_eq!(entries.len(), 2);

        // Header entry
        assert_eq!(entries[0].component.as_deref(), Some("MSI-header"));
        assert_eq!(entries[0].severity, Severity::Info);
        assert!(entries[0].timestamp.is_some());
        assert_eq!(
            entries[0].timestamp_display.as_deref(),
            Some("06-13-2023 09:02:46.000")
        );

        // Engine entry inherits the date
        assert_eq!(entries[1].component.as_deref(), Some("MSI-client"));
        assert!(entries[1].timestamp.is_some());
        assert_eq!(
            entries[1].timestamp_display.as_deref(),
            Some("06-13-2023 09:02:46.452")
        );
    }

    // -- Engine message parsing --

    #[test]
    fn test_parse_engine_message() {
        let lines = [
            "=== Verbose logging started: 1/15/2024  7:42:28  Build type: SHIP ===",
            "MSI (c) (8C:98) [07:42:28:452]: Resetting cached policy values",
        ];

        let (entries, _) = parse_lines(&lines, "test.log");

        assert_eq!(entries[1].message, "Resetting cached policy values");
        assert_eq!(entries[1].component.as_deref(), Some("MSI-client"));
        assert_eq!(entries[1].thread_display.as_deref(), Some("8C:98"));
        assert_eq!(entries[1].thread, Some(0x98));
        assert_eq!(entries[1].severity, Severity::Info);
    }

    #[test]
    fn test_parse_engine_server_context() {
        let lines = ["MSI (s) (4A:B0) [10:00:00:000]: Server running"];

        let (entries, _) = parse_lines(&lines, "test.log");

        assert_eq!(entries[0].component.as_deref(), Some("MSI-server"));
        assert_eq!(entries[0].thread_display.as_deref(), Some("4A:B0"));
        assert_eq!(entries[0].thread, Some(0xB0));
    }

    #[test]
    fn test_parse_engine_action_context() {
        let lines = ["MSI (a) (4A:B0) [10:00:00:000]: Custom action started"];

        let (entries, _) = parse_lines(&lines, "test.log");
        assert_eq!(entries[0].component.as_deref(), Some("MSI-action"));
    }

    // -- Action lines --

    #[test]
    fn test_parse_action_start() {
        let lines = [
            "=== Verbose logging started: 1/1/2024  16:34:00  Build type: SHIP ===",
            "Action start 16:34:29: InstallFiles.",
        ];

        let (entries, _) = parse_lines(&lines, "test.log");

        assert_eq!(entries[1].component.as_deref(), Some("InstallFiles"));
        assert_eq!(entries[1].severity, Severity::Info);
        assert!(entries[1].timestamp.is_some());
    }

    #[test]
    fn test_parse_action_ended_success() {
        let lines = [
            "=== Verbose logging started: 1/1/2024  16:34:00  Build type: SHIP ===",
            "Action ended 16:34:29: InstallFiles. Return value 1.",
        ];

        let (entries, _) = parse_lines(&lines, "test.log");

        assert_eq!(entries[1].component.as_deref(), Some("InstallFiles"));
        assert_eq!(entries[1].severity, Severity::Info);
    }

    #[test]
    fn test_parse_action_ended_error() {
        let lines = [
            "=== Verbose logging started: 1/1/2024  16:34:00  Build type: SHIP ===",
            "Action ended 16:34:29: InstallFiles. Return value 3.",
        ];

        let (entries, _) = parse_lines(&lines, "test.log");
        assert_eq!(entries[1].severity, Severity::Error);
    }

    #[test]
    fn test_parse_action_ended_warning() {
        let lines = ["Action ended 16:34:29: InstallFiles. Return value 2."];

        let (entries, _) = parse_lines(&lines, "test.log");
        assert_eq!(entries[0].severity, Severity::Warning);
    }

    // -- Property dump --

    #[test]
    fn test_parse_property() {
        let lines = ["Property(C): ProductCode = {C64CA371-1234-5678-9ABC-DEF012345678}"];

        let (entries, _) = parse_lines(&lines, "test.log");

        assert_eq!(entries[0].component.as_deref(), Some("MSI-properties"));
        assert_eq!(
            entries[0].message,
            "ProductCode = {C64CA371-1234-5678-9ABC-DEF012345678}"
        );
        assert_eq!(entries[0].severity, Severity::Info);
        assert!(entries[0].timestamp.is_none());
    }

    // -- MainEngineThread --

    #[test]
    fn test_main_engine_thread_success() {
        let lines = ["MainEngineThread is returning 0"];

        let (entries, _) = parse_lines(&lines, "test.log");
        assert_eq!(entries[0].severity, Severity::Info);
        assert_eq!(entries[0].component.as_deref(), Some("MSI-engine"));
    }

    #[test]
    fn test_main_engine_thread_error_1603() {
        let lines = ["MainEngineThread is returning 1603"];

        let (entries, _) = parse_lines(&lines, "test.log");
        assert_eq!(entries[0].severity, Severity::Error);
    }

    #[test]
    fn test_main_engine_thread_warning_1602() {
        let lines = ["MainEngineThread is returning 1602"];

        let (entries, _) = parse_lines(&lines, "test.log");
        assert_eq!(entries[0].severity, Severity::Warning);
    }

    // -- Footer --

    #[test]
    fn test_parse_footer() {
        let lines = ["=== Verbose logging stopped: 6/13/2023  9:03:15 ==="];

        let (entries, errors) = parse_lines(&lines, "test.log");

        assert_eq!(errors, 0);
        assert_eq!(entries[0].severity, Severity::Info);
        assert_eq!(entries[0].component.as_deref(), Some("MSI-header"));
    }

    // -- Fallback and error severity --

    #[test]
    fn test_plain_text_fallback() {
        let lines = ["Some random unstructured text"];

        let (entries, errors) = parse_lines(&lines, "test.log");

        assert_eq!(errors, 1);
        assert_eq!(entries[0].severity, Severity::Info);
        assert!(entries[0].component.is_none());
    }

    #[test]
    fn test_engine_error_keyword_severity() {
        let lines = ["MSI (c) (8C:98) [10:00:00:000]: Installation failed with error status: 1603"];

        let (entries, _) = parse_lines(&lines, "test.log");
        assert_eq!(entries[0].severity, Severity::Error);
    }

    // -- Midnight rollover --

    #[test]
    fn test_midnight_rollover() {
        let lines = [
            "=== Verbose logging started: 1/15/2024  23:59:50  Build type: SHIP ===",
            "MSI (c) (8C:98) [23:59:55:000]: Before midnight",
            "MSI (c) (8C:98) [00:00:05:000]: After midnight",
        ];

        let (entries, _) = parse_lines(&lines, "test.log");

        // After midnight should be Jan 16
        assert!(entries[2].timestamp.is_some());
        assert_eq!(
            entries[2].timestamp_display.as_deref(),
            Some("01-16-2024 00:00:05.000")
        );
    }

    // -- Empty and whitespace lines --

    #[test]
    fn test_empty_lines_skipped() {
        let lines = ["", "  ", "MSI (c) (8C:98) [10:00:00:000]: Hello", ""];

        let (entries, _) = parse_lines(&lines, "test.log");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].message, "Hello");
    }

    // -- Sequential IDs and line numbers --

    #[test]
    fn test_ids_and_line_numbers() {
        let lines = [
            "=== Verbose logging started: 1/1/2024  10:00:00  Build type: SHIP ===",
            "MSI (c) (8C:98) [10:00:01:000]: First",
            "MSI (c) (8C:98) [10:00:02:000]: Second",
        ];

        let (entries, _) = parse_lines(&lines, "test.log");

        assert_eq!(entries[0].id, 0);
        assert_eq!(entries[0].line_number, 1);
        assert_eq!(entries[1].id, 1);
        assert_eq!(entries[1].line_number, 2);
        assert_eq!(entries[2].id, 2);
        assert_eq!(entries[2].line_number, 3);
    }

    // -- Timestamp display format --

    #[test]
    fn test_timestamp_display_format() {
        let lines = [
            "=== Verbose logging started: 12/25/2023  8:30:15  Build type: SHIP ===",
            "MSI (c) (FF:01) [08:30:15:007]: Test message",
        ];

        let (entries, _) = parse_lines(&lines, "test.log");

        // Display should be MM-dd-yyyy HH:mm:ss.fff
        assert_eq!(
            entries[1].timestamp_display.as_deref(),
            Some("12-25-2023 08:30:15.007")
        );
    }

    // -- No date: time-only display --

    #[test]
    fn test_engine_without_header_has_time_only_display() {
        let lines = ["MSI (c) (8C:98) [14:30:00:123]: No header yet"];

        let (entries, _) = parse_lines(&lines, "test.log");

        assert!(entries[0].timestamp.is_none());
        assert_eq!(
            entries[0].timestamp_display.as_deref(),
            Some("14:30:00.123")
        );
    }

    // -- File path propagation --

    #[test]
    fn test_file_path_propagated() {
        let lines = ["MSI (c) (8C:98) [10:00:00:000]: Test"];

        let (entries, _) = parse_lines(&lines, "C:/Logs/install.log");
        assert_eq!(entries[0].file_path, "C:/Logs/install.log");
    }

    // -- LogFormat is Timestamped --

    #[test]
    fn test_log_format_is_timestamped() {
        let lines = [
            "MSI (c) (8C:98) [10:00:00:000]: Test",
            "Property(C): Foo = Bar",
            "Random line",
        ];

        let (entries, _) = parse_lines(&lines, "test.log");

        for entry in &entries {
            assert_eq!(entry.format, LogFormat::Timestamped);
        }
    }
}