cmtrace-open 1.5.0

Free, open-source CMTrace replacement: Windows log viewer with ConfigMgr/SCCM, Intune, and Autopilot ESP diagnostics, DSRegCmd triage, and real-time tailing.
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
//! Software Deployment workspace backend.
//!
//! Scans a folder recursively for deployment logs (MSI, PSADT, Burn, PatchMyPC),
//! classifies each file's format and outcome, extracts exit codes and error context,
//! and returns structured results for the frontend workspace.

use rayon::prelude::*;
use regex::Regex;
use serde::Serialize;
use std::path::Path;

use crate::error_db::lookup::lookup_error_code;
use crate::models::log_entry::{LogEntry, ParserKind, Severity};
use crate::parser;
use crate::parser::burn;
use std::sync::OnceLock;

// ── Types ────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub enum DeploymentFormat {
    #[serde(rename = "psadt-cmtrace")]
    PsadtCmtrace,
    #[serde(rename = "psadt-legacy")]
    PsadtLegacy,
    #[serde(rename = "msi-verbose")]
    MsiVerbose,
    #[serde(rename = "psadt-wrapper")]
    PsadtWrapper,
    #[serde(rename = "burn")]
    Burn,
    #[serde(rename = "patchmypc")]
    PatchMyPc,
    #[serde(rename = "unknown")]
    Unknown,
}

#[derive(Debug, Clone, Serialize)]
pub enum DeploymentOutcome {
    #[serde(rename = "success")]
    Success,
    #[serde(rename = "failure")]
    Failure,
    #[serde(rename = "deferred")]
    Deferred,
    #[serde(rename = "unknown")]
    Unknown,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeploymentErrorLine {
    pub line_number: u32,
    pub message: String,
    pub severity: String,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeploymentLogFile {
    pub path: String,
    pub file_name: String,
    pub format: DeploymentFormat,
    pub outcome: DeploymentOutcome,
    pub exit_code: Option<i32>,
    pub error_summary: Option<String>,
    pub error_lines: Vec<DeploymentErrorLine>,
    pub app_name: Option<String>,
    pub app_version: Option<String>,
    pub deploy_type: Option<String>,
    pub start_time: Option<String>,
    pub end_time: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeploymentAnalysisResult {
    pub folder_path: String,
    pub files: Vec<DeploymentLogFile>,
    pub total_files: usize,
    pub succeeded: usize,
    pub failed: usize,
    pub deferred: usize,
    pub unknown: usize,
}

// ── Regex patterns ───────────────────────────────────────────────────────

fn msi_main_engine_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"MainEngineThread is returning (\d+)").unwrap())
}

fn msi_return_value_3_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"Return value 3\b").unwrap())
}

fn psadt_exit_code_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"(?i)exit\s*code\s*[\[:\s]*(\d+)").unwrap())
}

/// Burn exit code: "Exit code: 0x0" or "Exit code: 0x80070005" (hex)
fn burn_exit_code_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"(?i)exit\s*code:\s*0x([0-9A-Fa-f]+)").unwrap())
}

// MSI metadata: Property(S): ProductName = <value>
fn msi_product_name_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"Property\(S\):\s*ProductName\s*=\s*(.+)").unwrap())
}

fn msi_product_version_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"Property\(S\):\s*ProductVersion\s*=\s*(.+)").unwrap())
}

// PSADT: Open-ADTSession message contains [Vendor Name Version]
// e.g., "Open-ADTSession [Contoso Foo App 1.2.3]" or in component field
fn psadt_session_info_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"\[([^\]]+)\]").unwrap())
}

// Burn: first i001 line e.g. "Burn v3.14.1.8722, Windows v10.0"
fn burn_version_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"Burn v([\d.]+)").unwrap())
}

// PatchMyPC: "Starting UserNotification V2.1.100.317"
fn patchmypc_version_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"(?i)Starting\s+UserNotification\s+V([\d.]+)").unwrap())
}

// MSI command line: /i = install, /x = uninstall, /f = repair
fn msi_cmdline_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r"(?i)CommandLine:\s+(.*)").unwrap())
}

// PSADT deploy type: "installationType [Install]" or in the session message
fn psadt_deploy_type_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(r"(?i)(?:deployment\s*type|installation\s*type|deploy\s*mode)\s*[:\s]*\[?\s*(Install|Uninstall|Repair)\b").unwrap()
})
}

// ── PSADT keywords ──────────────────────────────────────────────────────

const PSADT_KEYWORDS: &[&str] = &[
    "Open-ADTSession",
    "Close-ADTSession",
    "PSAppDeployToolkit",
    "Start-ADTMsiProcess",
    "ADTSession",
];

// ── Format classification ───────────────────────────────────────────────

fn classify_format(
    parser_kind: ParserKind,
    entries: &[LogEntry],
    file_path: &str,
) -> DeploymentFormat {
    match parser_kind {
        ParserKind::Msi => DeploymentFormat::MsiVerbose,
        ParserKind::PsadtLegacy => DeploymentFormat::PsadtLegacy,
        ParserKind::Burn => DeploymentFormat::Burn,
        ParserKind::Ccm => {
            let has_psadt = entries.iter().any(|e| {
                PSADT_KEYWORDS.iter().any(|kw| e.message.contains(kw))
                    || e.component
                        .as_deref()
                        .is_some_and(|c| PSADT_KEYWORDS.iter().any(|kw| c.contains(kw)))
            });
            if has_psadt {
                DeploymentFormat::PsadtCmtrace
            } else if file_path.to_ascii_lowercase().contains("patchmypc") {
                DeploymentFormat::PatchMyPc
            } else {
                DeploymentFormat::PsadtWrapper
            }
        }
        // Burn logs may be detected as Timestamped or Plain when the first 20
        // lines don't contain enough `[hex:hex][ISO-date]` records. Fall back
        // to a content scan of the raw entry messages.
        ParserKind::Timestamped | ParserKind::Plain => {
            let burn_matches = entries
                .iter()
                .take(50)
                .filter(|e| burn::matches_burn_record(e.message.trim()))
                .count();
            if burn_matches >= 2 {
                DeploymentFormat::Burn
            } else {
                DeploymentFormat::Unknown
            }
        }
        _ => DeploymentFormat::Unknown,
    }
}

// ── App metadata extraction ─────────────────────────────────────────────

fn extract_app_metadata(
    format: &DeploymentFormat,
    entries: &[LogEntry],
) -> (Option<String>, Option<String>) {
    match format {
        DeploymentFormat::MsiVerbose => {
            let mut name = None;
            let mut version = None;
            for entry in entries.iter() {
                if name.is_none() {
                    if let Some(caps) = msi_product_name_re().captures(&entry.message) {
                        name = Some(caps[1].trim().to_string());
                    }
                }
                if version.is_none() {
                    if let Some(caps) = msi_product_version_re().captures(&entry.message) {
                        version = Some(caps[1].trim().to_string());
                    }
                }
                if name.is_some() && version.is_some() {
                    break;
                }
            }
            (name, version)
        }
        DeploymentFormat::PsadtCmtrace | DeploymentFormat::PsadtWrapper => {
            // Look for Open-ADTSession in message text
            for entry in entries.iter() {
                if entry.message.contains("Open-ADTSession") {
                    if let Some(caps) = psadt_session_info_re().captures(&entry.message) {
                        let info = caps[1].trim().to_string();
                        return parse_psadt_app_info(&info);
                    }
                }
            }
            (None, None)
        }
        DeploymentFormat::PsadtLegacy => {
            // Component field is the source function name
            for entry in entries.iter() {
                let is_open = entry
                    .component
                    .as_deref()
                    .is_some_and(|c| c.contains("Open-ADTSession"));
                if is_open {
                    if let Some(caps) = psadt_session_info_re().captures(&entry.message) {
                        let info = caps[1].trim().to_string();
                        return parse_psadt_app_info(&info);
                    }
                }
            }
            (None, None)
        }
        DeploymentFormat::Burn => {
            // First i001 message: "Burn v3.14.1.8722, Windows v10.0..."
            for entry in entries.iter() {
                let is_i001 = entry.component.as_deref().is_some_and(|c| c == "i001");
                if is_i001 {
                    let version = burn_version_re()
                        .captures(&entry.message)
                        .map(|c| c[1].to_string());
                    // Use the full message as app name (it often has the product info)
                    let name = Some(entry.message.clone());
                    return (name, version);
                }
            }
            (None, None)
        }
        DeploymentFormat::PatchMyPc => {
            for entry in entries.iter() {
                if let Some(caps) = patchmypc_version_re().captures(&entry.message) {
                    return (
                        Some("PatchMyPC UserNotification".to_string()),
                        Some(caps[1].to_string()),
                    );
                }
            }
            (Some("PatchMyPC".to_string()), None)
        }
        DeploymentFormat::Unknown => (None, None),
    }
}

/// Parse PSADT app info from "[Vendor Name Version]" bracket content.
/// The convention is "Vendor AppName Version" but the fields aren't quoted.
/// Heuristic: if the last token looks like a version (digits/dots), split it off.
fn parse_psadt_app_info(info: &str) -> (Option<String>, Option<String>) {
    let parts: Vec<&str> = info.rsplitn(2, ' ').collect();
    if parts.len() == 2 {
        let maybe_version = parts[0];
        let maybe_name = parts[1];
        // Check if last token looks like a version (starts with a digit)
        if maybe_version.starts_with(|c: char| c.is_ascii_digit()) {
            return (
                Some(maybe_name.to_string()),
                Some(maybe_version.to_string()),
            );
        }
    }
    // Can't split — return the whole thing as the app name
    (Some(info.to_string()), None)
}

// ── Deploy type extraction ──────────────────────────────────────────────

fn extract_deploy_type(format: &DeploymentFormat, entries: &[LogEntry]) -> Option<String> {
    match format {
        DeploymentFormat::MsiVerbose => {
            for entry in entries.iter() {
                if let Some(caps) = msi_cmdline_re().captures(&entry.message) {
                    let cmd = caps[1].to_ascii_lowercase();
                    if cmd.contains("/x") || cmd.contains("remove=all") {
                        return Some("Uninstall".to_string());
                    }
                    if cmd.contains("/f") {
                        return Some("Repair".to_string());
                    }
                    if cmd.contains("/i") || cmd.contains("/qn") || cmd.contains("/qb") {
                        return Some("Install".to_string());
                    }
                }
            }
            // Default for MSI with no clear command line
            Some("Install".to_string())
        }
        DeploymentFormat::PsadtCmtrace
        | DeploymentFormat::PsadtWrapper
        | DeploymentFormat::PsadtLegacy => {
            for entry in entries.iter() {
                let text = &entry.message;
                if let Some(caps) = psadt_deploy_type_re().captures(text) {
                    let dt = caps[1].to_string();
                    // Capitalize first letter
                    let mut chars = dt.chars();
                    let capitalized = match chars.next() {
                        Some(c) => {
                            c.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase()
                        }
                        None => dt,
                    };
                    return Some(capitalized);
                }
            }
            None
        }
        _ => None,
    }
}

// ── Timestamp extraction ────────────────────────────────────────────────

fn extract_timestamps(entries: &[LogEntry]) -> (Option<String>, Option<String>) {
    let start = entries
        .iter()
        .find(|e| e.timestamp_display.is_some())
        .and_then(|e| e.timestamp_display.clone());
    let end = entries
        .iter()
        .rev()
        .find(|e| e.timestamp_display.is_some())
        .and_then(|e| e.timestamp_display.clone());
    (start, end)
}

// ── Exit code extraction ────────────────────────────────────────────────

fn extract_exit_code(format: &DeploymentFormat, entries: &[LogEntry]) -> Option<i32> {
    match format {
        DeploymentFormat::MsiVerbose => {
            for entry in entries.iter().rev() {
                if let Some(caps) = msi_main_engine_re().captures(&entry.message) {
                    if let Ok(code) = caps[1].parse::<i32>() {
                        return Some(code);
                    }
                }
            }
            None
        }
        DeploymentFormat::PsadtCmtrace
        | DeploymentFormat::PsadtWrapper
        | DeploymentFormat::PatchMyPc => {
            // Search for Close-ADTSession with exit code
            for entry in entries.iter().rev() {
                if entry.message.contains("Close-ADTSession")
                    || entry.message.contains("ADTSession")
                {
                    if let Some(caps) = psadt_exit_code_re().captures(&entry.message) {
                        if let Ok(code) = caps[1].parse::<i32>() {
                            return Some(code);
                        }
                    }
                }
            }
            // Fallback: any exit code pattern
            for entry in entries.iter().rev() {
                if let Some(caps) = psadt_exit_code_re().captures(&entry.message) {
                    if let Ok(code) = caps[1].parse::<i32>() {
                        return Some(code);
                    }
                }
            }
            None
        }
        DeploymentFormat::PsadtLegacy => {
            // Component field is the source function name
            for entry in entries.iter().rev() {
                let is_close = entry
                    .component
                    .as_deref()
                    .is_some_and(|c| c.contains("Close-ADTSession"));
                if is_close {
                    if let Some(caps) = psadt_exit_code_re().captures(&entry.message) {
                        if let Ok(code) = caps[1].parse::<i32>() {
                            return Some(code);
                        }
                    }
                }
            }
            for entry in entries.iter().rev() {
                if let Some(caps) = psadt_exit_code_re().captures(&entry.message) {
                    if let Ok(code) = caps[1].parse::<i32>() {
                        return Some(code);
                    }
                }
            }
            None
        }
        DeploymentFormat::Burn => {
            // Burn exit line: "Exit code: 0xN" (any severity, typically i007)
            for entry in entries.iter().rev() {
                if let Some(caps) = burn_exit_code_re().captures(&entry.message) {
                    if let Ok(code) = u32::from_str_radix(&caps[1], 16) {
                        return Some(code as i32);
                    }
                }
            }
            None
        }
        DeploymentFormat::Unknown => None,
    }
}

// ── Outcome classification ──────────────────────────────────────────────

fn classify_outcome(exit_code: Option<i32>) -> DeploymentOutcome {
    match exit_code {
        Some(0) | Some(3010) | Some(1641) => DeploymentOutcome::Success,
        Some(1602) | Some(1604) | Some(60012) | Some(70001) => DeploymentOutcome::Deferred,
        Some(_) => DeploymentOutcome::Failure,
        None => DeploymentOutcome::Unknown,
    }
}

// ── Error context extraction ────────────────────────────────────────────

fn extract_error_lines(
    format: &DeploymentFormat,
    entries: &[LogEntry],
) -> Vec<DeploymentErrorLine> {
    let mut lines = Vec::new();

    match format {
        DeploymentFormat::MsiVerbose => {
            // Find "Return value 3" lines with context
            for (i, entry) in entries.iter().enumerate() {
                if msi_return_value_3_re().is_match(&entry.message) {
                    let start = i.saturating_sub(3);
                    for ctx in &entries[start..=i] {
                        lines.push(DeploymentErrorLine {
                            line_number: ctx.line_number,
                            message: ctx.message.clone(),
                            severity: "Error".to_string(),
                        });
                    }
                }
            }
            // Include MainEngineThread line
            for entry in entries.iter() {
                if msi_main_engine_re().is_match(&entry.message) {
                    lines.push(DeploymentErrorLine {
                        line_number: entry.line_number,
                        message: entry.message.clone(),
                        severity: "Error".to_string(),
                    });
                }
            }
        }
        _ => {
            for entry in entries.iter() {
                match entry.severity {
                    Severity::Error => {
                        lines.push(DeploymentErrorLine {
                            line_number: entry.line_number,
                            message: entry.message.clone(),
                            severity: "Error".to_string(),
                        });
                    }
                    Severity::Warning => {
                        lines.push(DeploymentErrorLine {
                            line_number: entry.line_number,
                            message: entry.message.clone(),
                            severity: "Warning".to_string(),
                        });
                    }
                    _ => {}
                }
            }
        }
    }

    lines.truncate(50);
    lines
}

// ── Error summary ───────────────────────────────────────────────────────

fn generate_error_summary(
    format: &DeploymentFormat,
    exit_code: Option<i32>,
    outcome: &DeploymentOutcome,
) -> Option<String> {
    match outcome {
        DeploymentOutcome::Success | DeploymentOutcome::Unknown => return None,
        _ => {}
    }

    let code = exit_code?;
    let lookup = lookup_error_code(&code.to_string());

    let prefix = match format {
        DeploymentFormat::MsiVerbose => "MSI",
        DeploymentFormat::PsadtCmtrace
        | DeploymentFormat::PsadtLegacy
        | DeploymentFormat::PsadtWrapper => "PSADT",
        DeploymentFormat::Burn => "Burn",
        DeploymentFormat::PatchMyPc => "PatchMyPC",
        DeploymentFormat::Unknown => "Deployment",
    };

    if lookup.found {
        Some(format!(
            "{} exit code {}: {}",
            prefix, code, lookup.description
        ))
    } else {
        Some(format!("{} exit code {}", prefix, code))
    }
}

// ── Single file analysis ────────────────────────────────────────────────

fn analyze_single_file(file_path: &str) -> DeploymentLogFile {
    let path_obj = Path::new(file_path);
    let file_name = path_obj
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_else(|| file_path.to_string());

    match parser::parse_file(file_path) {
        Ok((result, resolved)) => {
            let format = classify_format(resolved.parser, &result.entries, file_path);
            let exit_code = extract_exit_code(&format, &result.entries);
            let outcome = classify_outcome(exit_code);
            let error_summary = generate_error_summary(&format, exit_code, &outcome);
            let error_lines = match outcome {
                DeploymentOutcome::Failure | DeploymentOutcome::Deferred => {
                    extract_error_lines(&format, &result.entries)
                }
                _ => Vec::new(),
            };
            let (app_name, app_version) = extract_app_metadata(&format, &result.entries);
            let deploy_type = extract_deploy_type(&format, &result.entries);
            let (start_time, end_time) = extract_timestamps(&result.entries);

            DeploymentLogFile {
                path: file_path.to_string(),
                file_name,
                format,
                outcome,
                exit_code,
                error_summary,
                error_lines,
                app_name,
                app_version,
                deploy_type,
                start_time,
                end_time,
            }
        }
        Err(_) => DeploymentLogFile {
            path: file_path.to_string(),
            file_name,
            format: DeploymentFormat::Unknown,
            outcome: DeploymentOutcome::Unknown,
            exit_code: None,
            error_summary: None,
            error_lines: Vec::new(),
            app_name: None,
            app_version: None,
            deploy_type: None,
            start_time: None,
            end_time: None,
        },
    }
}

// ── Recursive file enumeration ──────────────────────────────────────────

fn collect_log_files(dir: &Path, out: &mut Vec<String>) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_log_files(&path, out);
        } else if path.is_file() {
            if let Some(ext) = path.extension() {
                if ext.to_string_lossy().to_ascii_lowercase() == "log" {
                    out.push(path.to_string_lossy().to_string());
                }
            }
        }
    }
}

// ── Tauri command ───────────────────────────────────────────────────────

#[tauri::command]
pub fn analyze_deployment_folder(
    folder_path: String,
) -> Result<DeploymentAnalysisResult, crate::error::AppError> {
    let dir = Path::new(&folder_path);
    if !dir.is_dir() {
        return Err(crate::error::AppError::InvalidInput(format!(
            "Not a directory: {}",
            folder_path
        )));
    }

    let mut log_files = Vec::new();
    collect_log_files(dir, &mut log_files);

    if log_files.is_empty() {
        return Ok(DeploymentAnalysisResult {
            folder_path,
            files: Vec::new(),
            total_files: 0,
            succeeded: 0,
            failed: 0,
            deferred: 0,
            unknown: 0,
        });
    }

    // Parse all files in parallel
    let files: Vec<DeploymentLogFile> = log_files
        .par_iter()
        .map(|p| analyze_single_file(p))
        .collect();

    let mut succeeded = 0usize;
    let mut failed = 0usize;
    let mut deferred = 0usize;
    let mut unknown = 0usize;

    for file in &files {
        match file.outcome {
            DeploymentOutcome::Success => succeeded += 1,
            DeploymentOutcome::Failure => failed += 1,
            DeploymentOutcome::Deferred => deferred += 1,
            DeploymentOutcome::Unknown => unknown += 1,
        }
    }

    let total_files = files.len();

    Ok(DeploymentAnalysisResult {
        folder_path,
        files,
        total_files,
        succeeded,
        failed,
        deferred,
        unknown,
    })
}

// ── Tests ───────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::log_entry::LogFormat;

    fn make_entry(msg: &str, sev: Severity) -> LogEntry {
        make_entry_with_component(msg, sev, None)
    }

    fn make_entry_with_component(msg: &str, sev: Severity, component: Option<&str>) -> LogEntry {
        LogEntry {
            id: 0,
            line_number: 1,
            message: msg.to_string(),
            component: component.map(|s| s.to_string()),
            timestamp: None,
            timestamp_display: None,
            severity: sev,
            thread: None,
            thread_display: None,
            source_file: None,
            format: LogFormat::Plain,
            file_path: "test.log".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,
        }
    }

    #[test]
    fn test_outcome_success() {
        assert!(matches!(
            classify_outcome(Some(0)),
            DeploymentOutcome::Success
        ));
        assert!(matches!(
            classify_outcome(Some(3010)),
            DeploymentOutcome::Success
        ));
        assert!(matches!(
            classify_outcome(Some(1641)),
            DeploymentOutcome::Success
        ));
    }

    #[test]
    fn test_outcome_deferred() {
        assert!(matches!(
            classify_outcome(Some(1602)),
            DeploymentOutcome::Deferred
        ));
        assert!(matches!(
            classify_outcome(Some(60012)),
            DeploymentOutcome::Deferred
        ));
    }

    #[test]
    fn test_outcome_failure() {
        assert!(matches!(
            classify_outcome(Some(1603)),
            DeploymentOutcome::Failure
        ));
        assert!(matches!(
            classify_outcome(Some(1)),
            DeploymentOutcome::Failure
        ));
    }

    #[test]
    fn test_outcome_unknown() {
        assert!(matches!(classify_outcome(None), DeploymentOutcome::Unknown));
    }

    #[test]
    fn test_msi_exit_code() {
        let entries = vec![make_entry(
            "MainEngineThread is returning 1603",
            Severity::Error,
        )];
        assert_eq!(
            extract_exit_code(&DeploymentFormat::MsiVerbose, &entries),
            Some(1603)
        );
    }

    #[test]
    fn test_psadt_exit_code() {
        let entries = vec![make_entry(
            "Close-ADTSession completed with exit code [0]",
            Severity::Info,
        )];
        assert_eq!(
            extract_exit_code(&DeploymentFormat::PsadtCmtrace, &entries),
            Some(0)
        );
    }

    #[test]
    fn test_format_msi_direct() {
        let entries = vec![make_entry("test", Severity::Info)];
        assert!(matches!(
            classify_format(ParserKind::Msi, &entries, "test.log"),
            DeploymentFormat::MsiVerbose
        ));
    }

    #[test]
    fn test_format_burn_direct() {
        let entries = vec![make_entry("test", Severity::Info)];
        assert!(matches!(
            classify_format(ParserKind::Burn, &entries, "test.log"),
            DeploymentFormat::Burn
        ));
    }

    #[test]
    fn test_format_burn_fallback_from_timestamped() {
        let entries = vec![
            make_entry(
                "[07A4:0CBC][2025-11-25T01:55:42]i001: Burn v3.14.1.8722, Windows v10.0",
                Severity::Info,
            ),
            make_entry(
                "[07A4:0CBC][2025-11-25T01:55:43]i000: Initializing",
                Severity::Info,
            ),
        ];
        assert!(matches!(
            classify_format(ParserKind::Timestamped, &entries, "setup.exe.log"),
            DeploymentFormat::Burn
        ));
    }

    #[test]
    fn test_format_burn_fallback_from_plain() {
        let entries = vec![
            make_entry(
                "[1234:5678][2025-11-25T01:55:42]i001: Started bootstrapper",
                Severity::Info,
            ),
            make_entry(
                "[1234:5678][2025-11-25T01:55:43]e000: Error occurred",
                Severity::Error,
            ),
        ];
        assert!(matches!(
            classify_format(ParserKind::Plain, &entries, "installer.exe.log"),
            DeploymentFormat::Burn
        ));
    }

    #[test]
    fn test_format_plain_stays_unknown() {
        let entries = vec![
            make_entry("Just some plain text", Severity::Info),
            make_entry("No burn patterns here", Severity::Info),
        ];
        assert!(matches!(
            classify_format(ParserKind::Plain, &entries, "random.log"),
            DeploymentFormat::Unknown
        ));
    }

    #[test]
    fn test_format_ccm_with_psadt() {
        let entries = vec![make_entry("Open-ADTSession starting", Severity::Info)];
        assert!(matches!(
            classify_format(ParserKind::Ccm, &entries, "test.log"),
            DeploymentFormat::PsadtCmtrace
        ));
    }

    #[test]
    fn test_format_ccm_patchmypc() {
        let entries = vec![make_entry("starting up", Severity::Info)];
        assert!(matches!(
            classify_format(ParserKind::Ccm, &entries, "C:\\PatchMyPC\\Logs\\test.log"),
            DeploymentFormat::PatchMyPc
        ));
    }

    #[test]
    fn test_error_summary_with_known_code() {
        let summary = generate_error_summary(
            &DeploymentFormat::MsiVerbose,
            Some(1603),
            &DeploymentOutcome::Failure,
        );
        assert!(summary.is_some());
        assert!(summary.unwrap().contains("1603"));
    }

    #[test]
    fn test_error_summary_success_none() {
        assert!(generate_error_summary(
            &DeploymentFormat::MsiVerbose,
            Some(0),
            &DeploymentOutcome::Success
        )
        .is_none());
    }

    #[test]
    fn test_msi_app_metadata() {
        let entries = vec![
            make_entry("Property(S): ProductName = Contoso Widget", Severity::Info),
            make_entry("Property(S): ProductVersion = 2.3.1", Severity::Info),
        ];
        let (name, version) = extract_app_metadata(&DeploymentFormat::MsiVerbose, &entries);
        assert_eq!(name.as_deref(), Some("Contoso Widget"));
        assert_eq!(version.as_deref(), Some("2.3.1"));
    }

    #[test]
    fn test_psadt_app_metadata() {
        let entries = vec![make_entry(
            "Open-ADTSession [Contoso Foo App 1.2.3]",
            Severity::Info,
        )];
        let (name, version) = extract_app_metadata(&DeploymentFormat::PsadtCmtrace, &entries);
        assert_eq!(name.as_deref(), Some("Contoso Foo App"));
        assert_eq!(version.as_deref(), Some("1.2.3"));
    }

    #[test]
    fn test_burn_app_metadata() {
        let entries = vec![make_entry_with_component(
            "Burn v3.14.1.8722, Windows v10.0 (Build 26100)",
            Severity::Info,
            Some("i001"),
        )];
        let (name, version) = extract_app_metadata(&DeploymentFormat::Burn, &entries);
        assert!(name.is_some());
        assert!(name.unwrap().contains("Burn v3.14.1.8722"));
        assert_eq!(version.as_deref(), Some("3.14.1.8722"));
    }

    #[test]
    fn test_patchmypc_app_metadata() {
        let entries = vec![make_entry(
            "Starting UserNotification V2.1.100.317",
            Severity::Info,
        )];
        let (name, version) = extract_app_metadata(&DeploymentFormat::PatchMyPc, &entries);
        assert_eq!(name.as_deref(), Some("PatchMyPC UserNotification"));
        assert_eq!(version.as_deref(), Some("2.1.100.317"));
    }

    #[test]
    fn test_psadt_app_info_no_version() {
        let (name, version) = parse_psadt_app_info("SingleName");
        assert_eq!(name.as_deref(), Some("SingleName"));
        assert!(version.is_none());
    }

    #[test]
    fn test_msi_deploy_type_install() {
        let entries = vec![make_entry("CommandLine: /i setup.msi /qn", Severity::Info)];
        assert_eq!(
            extract_deploy_type(&DeploymentFormat::MsiVerbose, &entries).as_deref(),
            Some("Install")
        );
    }

    #[test]
    fn test_msi_deploy_type_uninstall() {
        let entries = vec![make_entry("CommandLine: /x {GUID} /qn", Severity::Info)];
        assert_eq!(
            extract_deploy_type(&DeploymentFormat::MsiVerbose, &entries).as_deref(),
            Some("Uninstall")
        );
    }

    #[test]
    fn test_psadt_deploy_type() {
        let entries = vec![make_entry("Deployment Type [Install]", Severity::Info)];
        assert_eq!(
            extract_deploy_type(&DeploymentFormat::PsadtCmtrace, &entries).as_deref(),
            Some("Install")
        );
    }

    #[test]
    fn test_timestamps_extraction() {
        let mut e1 = make_entry("first", Severity::Info);
        e1.timestamp_display = Some("2025-11-25 01:55:42.000".to_string());
        let mut e2 = make_entry("last", Severity::Info);
        e2.timestamp_display = Some("2025-11-25 02:10:00.000".to_string());
        let (start, end) = extract_timestamps(&[e1, e2]);
        assert_eq!(start.as_deref(), Some("2025-11-25 01:55:42.000"));
        assert_eq!(end.as_deref(), Some("2025-11-25 02:10:00.000"));
    }
}