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
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::OnceLock;

use regex::Regex;

use super::guid_registry::{self, guid_re, GuidRegistry};
use super::ime_parser::ImeLine;
use super::models::{IntuneEvent, IntuneEventType, IntuneStatus};

fn win32_app_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(
        r#"(?i)\[Win32App\].*(?:processing|executing|installing|detected|not detected|evaluating)"#,
    )
    .unwrap()
    })
}
fn win32_result_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)\[Win32App\].*(?:result|completed|success|failed|error)"#).unwrap()
    })
}
fn win32_guid_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(r#"(?i)(?:app|application)\s+(?:id|with\s+id)[:\s]+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"#).unwrap()
})
}
/// Matches "for app <GUID>" — common in StatusReport lines where a user GUID precedes the app GUID.
fn for_app_guid_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(
            r#"(?i)for\s+app\s+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})"#,
        )
        .unwrap()
    })
}
fn winget_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)WinGetApp.*(?:processing|installing|detected|evaluating)"#).unwrap()
    })
}
fn winget_token_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r#"(?i)(?:winget|microsoft\.winget)"#).unwrap())
}
fn appworkload_download_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:download(?:ing|ed)?|delivery\s+optimization|content\s+download|bytes\s+downloaded|download\s+progress|download\s+session|content\s+retrieval)"#,
    )
    .unwrap()
})
}
fn appworkload_staging_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:staging\s+(?:file|content)|hash\s+validation|content\s+cached|cache\s+location|expanded\s+content|extract(?:ed|ing))"#,
    )
    .unwrap()
})
}
fn appworkload_hash_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)(?:hash\s+validation|hash\s+mismatch|hash\s+check)"#).unwrap()
    })
}
fn appworkload_install_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:install(?:ing|ation)?|execution|enforcement|installer|launching\s+install|handoff\s+to\s+install|processdetectionrules|detection\s+rule)"#,
    )
    .unwrap()
})
}
fn appworkload_retry_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)(?:retry|retrying|reattempt|will\s+retry|attempt\s+\d+\s+of\s+\d+)"#)
            .unwrap()
    })
}
fn appworkload_stall_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:stalled|not\s+progressing|no\s+progress|timed?\s*out|timeout|hung|retry\s+exhausted)"#,
    )
    .unwrap()
})
}
fn appworkload_queue_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:queued|queueing|requesting\s+download|waiting\s+for\s+download|waiting\s+for\s+content|pending\s+download)"#,
    )
    .unwrap()
})
}
fn appworkload_failure_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:download\s+failed|failed\s+to\s+download|hash\s+validation\s+failed|hash\s+mismatch|staging\s+failed|unable\s+to\s+download|content\s+not\s+found|cancelled|aborted|retry\s+exhausted)"#,
    )
    .unwrap()
})
}
fn appworkload_success_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:download\s+completed|download\s+succeeded|staging\s+completed|content\s+cached|hash\s+validation\s+succeeded|install\s+completed|completed\s+successfully)"#,
    )
    .unwrap()
})
}
fn sidecar_script_start_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)start\s+detectionmanager\s+sidecarscriptdetectionmanager"#).unwrap()
    })
}
fn sidecar_script_complete_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)completed\s+detectionmanager\s+sidecarscriptdetectionmanager"#).unwrap()
    })
}
fn sidecar_script_mid_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)sidecarscriptdetectionmanager\s+(?:launch|process\s+id|powershell\s+exitcode|powershell\s+execution|create\s+proxy|execution\s+is\s+done|create\s+files)"#,
    )
    .unwrap()
})
}
fn sidecar_exitcode_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r#"(?i)powershell\s+exitcode:\s*(\d+)"#).unwrap())
}
fn policy_eval_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:assignment\s+evaluation|targeted\s+intent|applicability\s*=|\bapplicable\b|not\s+applicable|requirement\s+rule|detection\s+rule|local\s+deadline|grs\s+expired|grs\s+not\s+expired|enforcement\s+classification|will\s+not\s+be\s+enforced)"#,
    )
    .unwrap()
})
}
fn app_action_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)(?:app\s+with\s+id:|application\s+action|managed\s+app)"#).unwrap()
    })
}
fn applicability_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(r#"(?i)(?:applicability|applicable|not\s+applicable|requirement\s+rule|detection\s+rule|will\s+not\s+be\s+enforced)"#)
        .unwrap()
})
}
fn applicability_block_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:not\s+applicable|applicability\s*(?:=|:)\s*false|will\s+not\s+be\s+enforced|requirement\s+rule.*(?:not\s+satisfied|failed|false)|assignment.*(?:not\s+applicable|not\s+targeted)|enforcement\s+classification.*not\s+applicable)"#,
    )
    .unwrap()
})
}
fn applicability_success_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:applicability\s*(?:=|:)\s*true|requirement\s+rule.*(?:passed|satisfied|true)|assignment\s+evaluation\s+completed|applicable\s*=\s*true)"#,
    )
    .unwrap()
})
}
fn policy_pending_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)(?:local\s+deadline|grs\s+not\s+expired|scheduled|queued|pending)"#)
            .unwrap()
    })
}
fn script_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)(?:PowerShell\s+script|script\s+execution|running\s+script)"#).unwrap()
    })
}
fn script_result_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)script.*(?:completed|exit\s+code|result|output|failed|success)"#).unwrap()
    })
}
fn agentexecutor_script_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:powershell\s+script\s+is\s+successfully\s+executed|detection\s+script|remediation\s+script|exit\s+code|script\s+(?:completed|failed|timed?\s*out|execution)|stdout|stderr)"#,
    )
    .unwrap()
})
}
fn detection_script_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)\b(?:pre-)?detection\s+script\b|\bpre-detect\b"#).unwrap()
    })
}
fn remediation_script_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)\b(?:post-)?remediation\s+script\b|\bpost-detect\b|\bremediation\b"#)
            .unwrap()
    })
}
fn script_failure_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:access\s+is\s+denied|unauthorized|permission\s+denied|term\s+'.+'\s+is\s+not\s+recognized|cannot\s+find\s+path|path\s+not\s+found|file\s+not\s+found|module\s+.*\s+not\s+found|parsererror|syntax\s+error|execution\s+policy|digitally\s+signed|failed\s+to\s+execute|exception|stderr)"#,
    )
    .unwrap()
})
}
fn remediation_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)(?:Remediation|HealthScript|proactive\s+remediation)"#).unwrap()
    })
}
fn healthscript_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:healthscript|health\s+script|detection\s+script|remediation\s+script|pre-detect|post-detect|schedule(?:d|ing)?|compliance\s+result)"#,
    )
    .unwrap()
})
}
fn esp_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)(?:ESP|EspBody|EnrollmentStatusPage|enrollment\s+status)"#).unwrap()
    })
}
fn sync_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r#"(?i)(?:sync\s+session|check-in|SyncSession)"#).unwrap())
}
// GUID_RE imported from guid_registry
fn error_code_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:error\s*(?:code)?|exit\s*code(?:\s+of\s+the\s+script)?|hresult|hr|result|return\s*code)\s*(?:is|[=:])\s*(0x[0-9a-fA-F]+|-?\d+)"#,
    )
    .unwrap()
})
}
fn exit_code_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)exit\s*code(?:\s+of\s+the\s+script)?\s*(?:is|[=:])\s*(-?\d+)"#).unwrap()
    })
}
fn pending_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)(?:pending|queued|waiting|scheduled|requesting)"#).unwrap()
    })
}
fn timeout_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)(?:timed?\s*out|timeout|stalled|hung|not\s+progressing|no\s+progress)"#)
            .unwrap()
    })
}
fn compliance_true_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r#"(?i)compliance\s+result.*\bis\s+true\b"#).unwrap())
}
fn compliance_false_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r#"(?i)compliance\s+result.*\bis\s+false\b"#).unwrap())
}
fn client_health_rule_summary_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)summary:\s*rule\s+(.+?)\s+with\s+ID\s+[0-9a-f-]{36},\s*result\s*=\s*(pass|fail),\s*details\s*=\s*(.+)$"#,
    )
    .unwrap()
})
}
fn client_health_heartbeat_success_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)the client health report was sent successfully\. done\."#).unwrap()
    })
}
fn client_health_heartbeat_failure_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:failed to send heartbeat report|exception occurred while sending heartbeat report|clienthealthruleengine\]\(sendheartbeatreport\).*(?:failed|unauthorized|exception)|found webexception in aggregateexception)"#,
    )
    .unwrap()
})
}
fn client_cert_local_machine_count_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)MDM certs found in LocalMachine count:\s*(\d+)"#).unwrap()
    })
}
fn client_cert_failure_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:certificate.*(?:invalid|error|fail)|private key|correct oid|expired|client cert check.*exception|exception.*certificate)"#,
    )
    .unwrap()
})
}
fn device_health_app_crash_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?is)received application event.*?<Data Name="AppName">([^<]+)</Data>.*?<Data Name="ExceptionCode">([^<]+)</Data>"#,
    )
    .unwrap()
})
}
fn sensor_memory_failure_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:error getting physically installed system memory|GetPhysicallyInstalledSystemMemory failed)"#,
    )
    .unwrap()
})
}
fn win32_app_inventory_full_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| Regex::new(r#"(?i)\[Win32AppInventory\]\s*report type is 1\b"#).unwrap())
}
fn win32_app_inventory_no_change_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
        Regex::new(r#"(?i)no change detected in win32 app inventory delta update"#).unwrap()
    })
}
fn win32_app_inventory_delta_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)computing delta inventory\.\.\.done\.\s*add count\s*=\s*(\d+),\s*modify count\s*=\s*(\d+),\s*delete count\s*=\s*(\d+)"#,
    )
    .unwrap()
})
}
fn success_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:success|succeeded|completed\s+successfully|installed|detected|compliant|validated|passed)"#,
    )
    .unwrap()
})
}
fn failed_re() -> &'static Regex {
    static CELL: OnceLock<Regex> = OnceLock::new();
    CELL.get_or_init(|| {
    Regex::new(
        r#"(?i)(?:fail|error|not\s+detected|not\s+installed|non-compliant|cancelled|aborted|exception)"#,
    )
    .unwrap()
})
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ImeSourceKind {
    PrimaryIme,
    AppWorkload,
    AppActionProcessor,
    AgentExecutor,
    HealthScripts,
    ClientHealth,
    ClientCertCheck,
    DeviceHealthMonitoring,
    Sensor,
    Win32AppInventory,
    Other,
}

#[derive(Debug, Default, Clone, Copy)]
struct AppWorkloadMatchFlags {
    winget_token: bool,
    winget: bool,
    download: bool,
    staging: bool,
    hash: bool,
    install: bool,
    retry: bool,
    stall: bool,
    failure: bool,
    success: bool,
    queue: bool,
    pending: bool,
    timeout: bool,
    sidecar_script_start: bool,
    sidecar_script_complete: bool,
    sidecar_script_mid: bool,
}

impl AppWorkloadMatchFlags {
    fn from_message(msg: &str) -> Self {
        Self {
            winget_token: winget_token_re().is_match(msg),
            winget: winget_re().is_match(msg),
            download: appworkload_download_re().is_match(msg),
            staging: appworkload_staging_re().is_match(msg),
            hash: appworkload_hash_re().is_match(msg),
            install: appworkload_install_re().is_match(msg),
            retry: appworkload_retry_re().is_match(msg),
            stall: appworkload_stall_re().is_match(msg),
            failure: appworkload_failure_re().is_match(msg),
            success: appworkload_success_re().is_match(msg),
            queue: appworkload_queue_re().is_match(msg),
            pending: pending_re().is_match(msg),
            timeout: timeout_re().is_match(msg),
            sidecar_script_start: sidecar_script_start_re().is_match(msg),
            sidecar_script_complete: sidecar_script_complete_re().is_match(msg),
            sidecar_script_mid: sidecar_script_mid_re().is_match(msg),
        }
    }

    fn is_candidate(self) -> bool {
        self.download
            || self.staging
            || self.install
            || self.retry
            || self.stall
            || self.winget_token
            || self.winget
            || self.sidecar_script_start
            || self.sidecar_script_complete
            || self.sidecar_script_mid
    }
}

pub fn extract_events(
    lines: &[ImeLine],
    source_file: &str,
    registry: &GuidRegistry,
) -> Vec<IntuneEvent> {
    let mut events = Vec::new();
    let mut next_id = 0u64;
    let source_kind = classify_source_kind(source_file);

    for (index, line) in lines.iter().enumerate() {
        if source_kind == ImeSourceKind::AppWorkload {
            if let Some(event) =
                extract_appworkload_event(lines, index, line, source_file, next_id, registry)
            {
                events.push(event);
                next_id += 1;
            }
            continue;
        }

        let Some(event_type) = detect_event_type(&line.message, source_kind) else {
            continue;
        };

        // Try primary extract_guid, fall back to guid_registry::extract_app_id
        let guid =
            extract_guid(&line.message).or_else(|| guid_registry::extract_app_id(&line.message));
        let status = determine_status(&line.message, source_kind);
        let raw_name = build_event_name(&event_type, &guid, &line.message, source_kind);

        // Inline enrichment: resolve GUID suffix immediately if possible
        let name = match guid.as_deref() {
            Some(g) => registry.enrich_event_name(&raw_name, g).unwrap_or(raw_name),
            None => raw_name,
        };

        let detail = line.message.clone();

        events.push(IntuneEvent {
            id: next_id,
            event_type,
            name,
            guid,
            status,
            start_time: line
                .timestamp_utc
                .clone()
                .or_else(|| line.timestamp.clone()),
            end_time: None,
            duration_secs: None,
            error_code: extract_error_code(&line.message),
            detail,
            source_file: source_file.to_string(),
            line_number: line.line_number,
            start_time_epoch: None,
            end_time_epoch: None,
            script_body: None,
            parent_app_guid: None,
        });
        next_id += 1;
    }

    pair_events(&mut events);
    events
}

fn extract_appworkload_event(
    lines: &[ImeLine],
    index: usize,
    line: &ImeLine,
    source_file: &str,
    next_id: u64,
    registry: &GuidRegistry,
) -> Option<IntuneEvent> {
    let msg = line.message.as_str();
    if contains_any_ascii_case_insensitive(
        msg,
        &[
            "reportingmanager",
            "reportingcachemanager",
            "reporting state initialized",
            "sending reports",
            "writeabletostorage",
            "cangenerate",
            "isappreportable",
            "get policies",
        ],
    ) {
        return None;
    }

    let flags = AppWorkloadMatchFlags::from_message(msg);
    if !flags.is_candidate() {
        return None;
    }

    // Determine event type from flags
    let is_sidecar =
        flags.sidecar_script_start || flags.sidecar_script_complete || flags.sidecar_script_mid;

    let event_type = if flags.winget_token || flags.winget {
        IntuneEventType::WinGetApp
    } else if is_sidecar {
        IntuneEventType::PowerShellScript
    } else if flags.download || flags.staging || flags.retry || flags.stall {
        IntuneEventType::ContentDownload
    } else if flags.install {
        IntuneEventType::Win32App
    } else {
        return None;
    };

    // Try primary extract_guid, fall back to guid_registry::extract_app_id
    let guid = extract_guid(msg).or_else(|| guid_registry::extract_app_id(msg));

    if is_sidecar {
        let status = determine_sidecar_script_status(msg, flags);
        let error_code = sidecar_exitcode_re()
            .captures(msg)
            .and_then(|cap| cap.get(1))
            .map(|m| m.as_str().to_string());
        let short = guid
            .as_deref()
            .map(|g| &g[..8.min(g.len())])
            .unwrap_or("unknown");
        let phase = if flags.sidecar_script_complete {
            "Complete"
        } else if flags.sidecar_script_start {
            "Start"
        } else {
            "Running"
        };
        let raw_name = format!("Script Detection {phase} ({short})");

        let name = match guid.as_deref() {
            Some(g) => registry.enrich_event_name(&raw_name, g).unwrap_or(raw_name),
            None => raw_name,
        };

        return Some(IntuneEvent {
            id: next_id,
            event_type,
            name,
            guid: guid.clone(),
            status,
            start_time: line
                .timestamp_utc
                .clone()
                .or_else(|| line.timestamp.clone()),
            end_time: None,
            duration_secs: None,
            error_code,
            detail: msg.to_string(),
            source_file: source_file.to_string(),
            line_number: line.line_number,
            start_time_epoch: None,
            end_time_epoch: None,
            script_body: None,
            parent_app_guid: guid,
        });
    }

    let status = determine_appworkload_status(msg, flags);
    let raw_name = build_appworkload_name(&event_type, &guid, msg, flags);

    // Inline enrichment: resolve GUID suffix immediately if possible
    let name = match guid.as_deref() {
        Some(g) => registry.enrich_event_name(&raw_name, g).unwrap_or(raw_name),
        None => raw_name,
    };
    let detail = build_appworkload_detail(lines, index, guid.as_deref(), msg, status);

    Some(IntuneEvent {
        id: next_id,
        event_type,
        name,
        guid,
        status,
        start_time: line
            .timestamp_utc
            .clone()
            .or_else(|| line.timestamp.clone()),
        end_time: None,
        duration_secs: None,
        error_code: extract_error_code(msg),
        detail,
        source_file: source_file.to_string(),
        line_number: line.line_number,
        start_time_epoch: None,
        end_time_epoch: None,
        script_body: None,
        parent_app_guid: None,
    })
}

fn determine_appworkload_status(msg: &str, flags: AppWorkloadMatchFlags) -> IntuneStatus {
    if flags.stall || flags.timeout {
        IntuneStatus::Timeout
    } else if flags.retry || flags.failure {
        IntuneStatus::Failed
    } else if flags.success {
        IntuneStatus::Success
    } else if flags.queue || flags.pending || contains_ascii_case_insensitive(msg, "pending") {
        IntuneStatus::Pending
    } else {
        IntuneStatus::InProgress
    }
}

fn determine_sidecar_script_status(msg: &str, flags: AppWorkloadMatchFlags) -> IntuneStatus {
    if flags.sidecar_script_start {
        return IntuneStatus::InProgress;
    }
    if flags.sidecar_script_complete {
        // Detection complete — both detected and not-detected are successful detection runs.
        return IntuneStatus::Success;
    }
    // Mid-event: check exit code
    if let Some(cap) = sidecar_exitcode_re().captures(msg) {
        let code = cap.get(1).map_or("", |m| m.as_str());
        return if code == "0" {
            IntuneStatus::Success
        } else {
            IntuneStatus::Failed
        };
    }
    IntuneStatus::InProgress
}

fn build_appworkload_name(
    event_type: &IntuneEventType,
    guid: &Option<String>,
    msg: &str,
    flags: AppWorkloadMatchFlags,
) -> String {
    if *event_type == IntuneEventType::WinGetApp {
        return match guid.as_deref().map(short_guid) {
            Some(short) => format!("AppWorkload WinGet ({short})"),
            None => "AppWorkload WinGet".to_string(),
        };
    }

    let phase = if flags.stall {
        "Download Stall"
    } else if flags.retry {
        "Download Retry"
    } else if flags.hash {
        "Hash Validation"
    } else if flags.staging {
        "Staging"
    } else if flags.install {
        "Install"
    } else if flags.download {
        "Download"
    } else {
        return build_event_name(event_type, guid, msg, ImeSourceKind::AppWorkload);
    };

    match guid.as_deref().map(short_guid) {
        Some(short) => format!("AppWorkload {phase} ({short})"),
        None => format!("AppWorkload {phase}"),
    }
}

// When AppWorkload failures do not have clean subgraph markers nearby, fall back to a
// compact local window so the row still shows useful surrounding evidence.
const APPWORKLOAD_CONTEXT_RADIUS: usize = 10;
// Search a wider neighborhood for same-GUID lines because AppWorkload often emits
// reporting state or policy payload records well before the failure line itself.
const APPWORKLOAD_CONTEXT_LOOKAROUND: usize = 120;
// Cap the rendered context bundle so failed rows stay readable and the copied payload
// remains shareable without dragging in the entire file.
const APPWORKLOAD_CONTEXT_MAX_LINES: usize = 48;

fn build_appworkload_detail(
    lines: &[ImeLine],
    index: usize,
    guid: Option<&str>,
    msg: &str,
    status: IntuneStatus,
) -> String {
    if !matches!(status, IntuneStatus::Failed | IntuneStatus::Timeout) {
        return msg.to_string();
    }

    let context = collect_appworkload_context(lines, index, guid);
    if context.is_empty() {
        return msg.to_string();
    }

    format!("{msg}\n\nAppWorkload context:\n{}", context.join("\n"))
}

fn collect_appworkload_context(lines: &[ImeLine], index: usize, guid: Option<&str>) -> Vec<String> {
    if lines.is_empty() || index >= lines.len() {
        return Vec::new();
    }

    let (block_start, block_end) = find_appworkload_subgraph_bounds(lines, index);
    let mut selected = HashSet::new();
    for selected_index in block_start..=block_end {
        selected.insert(selected_index);
    }

    if let Some(guid) = guid {
        let lookaround_start = index.saturating_sub(APPWORKLOAD_CONTEXT_LOOKAROUND);
        let lookaround_end =
            (index + APPWORKLOAD_CONTEXT_LOOKAROUND).min(lines.len().saturating_sub(1));
        for (i, line) in lines[lookaround_start..=lookaround_end].iter().enumerate() {
            if contains_ascii_case_insensitive(&line.message, guid) {
                selected.insert(lookaround_start + i);
            }
        }
    }

    if selected.is_empty() {
        let fallback_start = index.saturating_sub(APPWORKLOAD_CONTEXT_RADIUS);
        let fallback_end = (index + APPWORKLOAD_CONTEXT_RADIUS).min(lines.len().saturating_sub(1));
        for selected_index in fallback_start..=fallback_end {
            selected.insert(selected_index);
        }
    }

    let mut indices = selected.into_iter().collect::<Vec<_>>();
    indices.sort_unstable();

    if indices.len() > APPWORKLOAD_CONTEXT_MAX_LINES {
        // Keep the lines closest to the failure first so trimmed bundles preserve the
        // immediate error context before more distant same-GUID references. For equally
        // distant lines, the lower line number wins so the final output stays chronological.
        indices.sort_by_key(|selected_index| (selected_index.abs_diff(index), *selected_index));
        indices.truncate(APPWORKLOAD_CONTEXT_MAX_LINES);
        indices.sort_unstable();
    }

    let mut formatted = Vec::with_capacity(indices.len());
    let mut previous_index = None;
    for selected_index in indices {
        if let Some(previous_index_value) = previous_index {
            if selected_index > previous_index_value + 1 {
                formatted.push(format!(
                    "… {} line(s) omitted …",
                    selected_index - previous_index_value - 1
                ));
            }
        }
        formatted.push(format_appworkload_context_line(
            &lines[selected_index],
            selected_index == index,
        ));
        previous_index = Some(selected_index);
    }

    formatted
}

fn find_appworkload_subgraph_bounds(lines: &[ImeLine], index: usize) -> (usize, usize) {
    if lines.is_empty() {
        return (0, 0);
    }

    let safe_index = index.min(lines.len() - 1);
    let mut start = safe_index;
    while start > 0 {
        let candidate = start - 1;
        let message = lines[candidate].message.as_str();
        if is_appworkload_subgraph_end(message) {
            break;
        }
        start = candidate;
        if is_appworkload_subgraph_start(message) {
            break;
        }
    }

    let mut end = safe_index;
    while end + 1 < lines.len() {
        let candidate = end + 1;
        let message = lines[candidate].message.as_str();
        if is_appworkload_subgraph_start(message) {
            break;
        }
        end = candidate;
        if is_appworkload_subgraph_end(message) {
            break;
        }
    }

    (start, end)
}

fn is_appworkload_subgraph_start(msg: &str) -> bool {
    contains_ascii_case_insensitive(msg, "processing subgraph with app ids:")
}

fn is_appworkload_subgraph_end(msg: &str) -> bool {
    contains_ascii_case_insensitive(msg, "done processing subgraph")
}

fn format_appworkload_context_line(line: &ImeLine, is_selected: bool) -> String {
    let marker = if is_selected { ">" } else { " " };
    let timestamp = line
        .timestamp_utc
        .as_deref()
        .or(line.timestamp.as_deref())
        .unwrap_or("No timestamp");
    format!(
        "{marker} L{} {timestamp} {}",
        line.line_number, line.message
    )
}

fn classify_source_kind(source_file: &str) -> ImeSourceKind {
    let file_name = Path::new(source_file)
        .file_name()
        .map(|name| name.to_string_lossy().to_ascii_lowercase())
        .unwrap_or_else(|| source_file.to_ascii_lowercase());

    if file_name.contains("appworkload") {
        ImeSourceKind::AppWorkload
    } else if file_name.contains("appactionprocessor") {
        ImeSourceKind::AppActionProcessor
    } else if file_name.contains("agentexecutor") {
        ImeSourceKind::AgentExecutor
    } else if file_name.contains("healthscripts") {
        ImeSourceKind::HealthScripts
    } else if file_name.contains("clienthealth") {
        ImeSourceKind::ClientHealth
    } else if file_name.contains("clientcertcheck") {
        ImeSourceKind::ClientCertCheck
    } else if file_name.contains("devicehealthmonitoring") {
        ImeSourceKind::DeviceHealthMonitoring
    } else if file_name.contains("sensor") {
        ImeSourceKind::Sensor
    } else if file_name.contains("win32appinventory") {
        ImeSourceKind::Win32AppInventory
    } else if file_name.contains("intunemanagementextension") {
        ImeSourceKind::PrimaryIme
    } else {
        ImeSourceKind::Other
    }
}

fn detect_event_type(msg: &str, source_kind: ImeSourceKind) -> Option<IntuneEventType> {
    match source_kind {
        ImeSourceKind::AppWorkload => {
            if !is_appworkload_event_candidate(msg) {
                return None;
            }
            if winget_token_re().is_match(msg) || winget_re().is_match(msg) {
                return Some(IntuneEventType::WinGetApp);
            }
            if appworkload_download_re().is_match(msg)
                || appworkload_staging_re().is_match(msg)
                || appworkload_retry_re().is_match(msg)
                || appworkload_stall_re().is_match(msg)
            {
                return Some(IntuneEventType::ContentDownload);
            }
            if appworkload_install_re().is_match(msg) {
                return Some(IntuneEventType::Win32App);
            }
        }
        ImeSourceKind::AppActionProcessor => {
            if is_app_action_processor_event_candidate(msg)
                && (policy_eval_re().is_match(msg)
                    || app_action_re().is_match(msg)
                    || applicability_re().is_match(msg))
            {
                return Some(IntuneEventType::PolicyEvaluation);
            }
        }
        ImeSourceKind::AgentExecutor => {
            if !is_agent_executor_event_candidate(msg) {
                return None;
            }
            if remediation_script_re().is_match(msg) || remediation_re().is_match(msg) {
                return Some(IntuneEventType::Remediation);
            }
            if agentexecutor_script_re().is_match(msg)
                || script_re().is_match(msg)
                || script_result_re().is_match(msg)
            {
                return Some(IntuneEventType::PowerShellScript);
            }
        }
        ImeSourceKind::HealthScripts => {
            if is_healthscripts_event_candidate(msg)
                && (healthscript_re().is_match(msg) || remediation_re().is_match(msg))
            {
                return Some(IntuneEventType::Remediation);
            }
        }
        ImeSourceKind::ClientHealth => {
            if is_client_health_event_candidate(msg) {
                return Some(IntuneEventType::Other);
            }
        }
        ImeSourceKind::ClientCertCheck => {
            if is_client_cert_check_event_candidate(msg) {
                return Some(IntuneEventType::Other);
            }
        }
        ImeSourceKind::DeviceHealthMonitoring => {
            if device_health_app_crash_re().is_match(msg) {
                return Some(IntuneEventType::Other);
            }
        }
        ImeSourceKind::Sensor => {
            if sensor_memory_failure_re().is_match(msg) {
                return Some(IntuneEventType::Other);
            }
        }
        ImeSourceKind::Win32AppInventory => {
            if is_win32_app_inventory_event_candidate(msg) {
                return Some(IntuneEventType::Other);
            }
        }
        ImeSourceKind::PrimaryIme | ImeSourceKind::Other => {}
    }

    if win32_app_re().is_match(msg) || win32_result_re().is_match(msg) {
        Some(IntuneEventType::Win32App)
    } else if winget_re().is_match(msg) {
        Some(IntuneEventType::WinGetApp)
    } else if script_re().is_match(msg) || script_result_re().is_match(msg) {
        Some(IntuneEventType::PowerShellScript)
    } else if remediation_re().is_match(msg) {
        Some(IntuneEventType::Remediation)
    } else if esp_re().is_match(msg) {
        Some(IntuneEventType::Esp)
    } else if sync_re().is_match(msg) {
        Some(IntuneEventType::SyncSession)
    } else {
        None
    }
}

fn is_agent_executor_event_candidate(msg: &str) -> bool {
    if ends_with_ascii_case_insensitive(msg, ".timeout")
        || ends_with_ascii_case_insensitive(msg, "quotedtimeoutfilepath.txt")
        || contains_any_ascii_case_insensitive(
            msg,
            &[
                "prepare to run powershell script",
                "remediation script option gets invoked",
                "creating command line parser",
                "adding argument",
                "powershell path is",
            ],
        )
    {
        return false;
    }

    contains_any_ascii_case_insensitive(
        msg,
        &[
            "powershell exit code",
            "powershell script is successfully executed",
            "detection script",
            "remediation script",
            "script completed",
            "script failed",
            "script execution",
            "timed out",
            "timeout",
            "stdout",
            "stderr",
            "exit code",
        ],
    )
}

fn is_appworkload_event_candidate(msg: &str) -> bool {
    if contains_any_ascii_case_insensitive(
        msg,
        &[
            "reportingmanager",
            "reportingcachemanager",
            "reporting state initialized",
            "sending reports",
            "writeabletostorage",
            "cangenerate",
            "isappreportable",
        ],
    ) {
        return false;
    }

    appworkload_download_re().is_match(msg)
        || appworkload_staging_re().is_match(msg)
        || appworkload_install_re().is_match(msg)
        || appworkload_retry_re().is_match(msg)
        || appworkload_stall_re().is_match(msg)
        || winget_token_re().is_match(msg)
}

fn is_app_action_processor_event_candidate(msg: &str) -> bool {
    !(contains_ascii_case_insensitive(msg, "processor initializing")
        || (contains_ascii_case_insensitive(msg, "found:")
            && contains_ascii_case_insensitive(msg, "apps with intent"))
        || contains_ascii_case_insensitive(
            msg,
            "evaluating install enforcement actions for app with id",
        )
        || contains_ascii_case_insensitive(msg, "no action required for app with id"))
        && contains_any_ascii_case_insensitive(
            msg,
            &[
                "app with id:",
                "assignment evaluation",
                "targeted intent",
                "applicability =",
                "not applicable",
                "local deadline",
                "grs expired",
                "grs not expired",
                "requirement rule",
                "detection rule",
                "will not be enforced",
            ],
        )
}

fn is_healthscripts_event_candidate(msg: &str) -> bool {
    if contains_any_ascii_case_insensitive(
        msg,
        &[
            "inspect hourly schedule",
            "job is queued and will be scheduled",
            "completed user session",
        ],
    ) {
        return false;
    }

    contains_any_ascii_case_insensitive(
        msg,
        &[
            "detection script",
            "remediation script",
            "exit code of the script",
            "compliance result",
            "pre-detect",
            "post-detect",
            "timed out",
            "timeout",
            "failed",
            "schedule",
        ],
    )
}

fn is_client_health_event_candidate(msg: &str) -> bool {
    client_health_heartbeat_success_re().is_match(msg)
        || client_health_heartbeat_failure_re().is_match(msg)
        || matches!(
            parse_client_health_summary(msg),
            Some((_, IntuneStatus::Failed, _))
        )
}

fn is_client_cert_check_event_candidate(msg: &str) -> bool {
    parse_client_cert_local_machine_count(msg) == Some(0) || client_cert_failure_re().is_match(msg)
}

fn is_win32_app_inventory_event_candidate(msg: &str) -> bool {
    win32_app_inventory_full_re().is_match(msg)
        || win32_app_inventory_no_change_re().is_match(msg)
        || matches!(parse_win32_app_inventory_delta(msg), Some((add, modify, delete)) if add > 0 || modify > 0 || delete > 0)
}

fn extract_guid(msg: &str) -> Option<String> {
    // 1. Specific "app id" / "application with id" pattern
    win32_guid_re()
        .captures(msg)
        .and_then(|cap| cap.get(1))
        .map(|value| value.as_str().to_string())
        // 2. "for app <GUID>" — avoids grabbing a user GUID that precedes the app GUID
        .or_else(|| {
            for_app_guid_re()
                .captures(msg)
                .and_then(|cap| cap.get(1))
                .map(|value| value.as_str().to_string())
        })
        // 3. PolicyId from JSON payloads (HealthScripts, script results)
        .or_else(|| extract_policy_id(msg))
        // 4. Generic first GUID fallback
        .or_else(|| {
            guid_re()
                .captures(msg)
                .and_then(|cap| cap.get(1))
                .map(|value| value.as_str().to_string())
        })
}

/// Extract PolicyId from JSON payloads in HealthScripts/script result messages.
/// Handles lines like: `"PolicyId":"79880037-a3c4-489a-a7e6-a6a705b52b78"`
fn extract_policy_id(msg: &str) -> Option<String> {
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| {
        Regex::new(r#"(?i)"PolicyId"\s*:\s*\\?"([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\\?""#).unwrap()
    });
    re.captures(msg)
        .and_then(|cap| cap.get(1))
        .map(|m| m.as_str().to_string())
}

fn extract_error_code(msg: &str) -> Option<String> {
    error_code_re()
        .captures(msg)
        .and_then(|cap| cap.get(1))
        .map(|value| value.as_str().to_string())
}

fn determine_status(msg: &str, source_kind: ImeSourceKind) -> IntuneStatus {
    if compliance_true_re().is_match(msg) {
        return IntuneStatus::Success;
    }
    if compliance_false_re().is_match(msg) {
        return IntuneStatus::Failed;
    }
    if let Some(exit_code) = exit_code_re()
        .captures(msg)
        .and_then(|cap| cap.get(1))
        .and_then(|value| value.as_str().parse::<i32>().ok())
    {
        return if exit_code == 0 {
            IntuneStatus::Success
        } else {
            IntuneStatus::Failed
        };
    }

    match source_kind {
        ImeSourceKind::AppWorkload => {
            if appworkload_stall_re().is_match(msg) || timeout_re().is_match(msg) {
                IntuneStatus::Timeout
            } else if appworkload_retry_re().is_match(msg) || appworkload_failure_re().is_match(msg)
            {
                IntuneStatus::Failed
            } else if appworkload_success_re().is_match(msg) {
                IntuneStatus::Success
            } else if appworkload_queue_re().is_match(msg) || pending_re().is_match(msg) {
                IntuneStatus::Pending
            } else {
                IntuneStatus::InProgress
            }
        }
        ImeSourceKind::AppActionProcessor => {
            if applicability_block_re().is_match(msg) {
                IntuneStatus::Failed
            } else if applicability_success_re().is_match(msg) {
                IntuneStatus::Success
            } else if policy_pending_re().is_match(msg) {
                IntuneStatus::Pending
            } else {
                IntuneStatus::InProgress
            }
        }
        ImeSourceKind::AgentExecutor | ImeSourceKind::HealthScripts => {
            if timeout_re().is_match(msg) {
                IntuneStatus::Timeout
            } else if script_failure_re().is_match(msg) || failed_re().is_match(msg) {
                IntuneStatus::Failed
            } else if success_re().is_match(msg) {
                IntuneStatus::Success
            } else if pending_re().is_match(msg) {
                IntuneStatus::Pending
            } else {
                IntuneStatus::InProgress
            }
        }
        ImeSourceKind::ClientHealth => {
            if let Some((_, status, _)) = parse_client_health_summary(msg) {
                status
            } else if client_health_heartbeat_failure_re().is_match(msg) {
                IntuneStatus::Failed
            } else if client_health_heartbeat_success_re().is_match(msg) {
                IntuneStatus::Success
            } else {
                IntuneStatus::Unknown
            }
        }
        ImeSourceKind::ClientCertCheck => {
            if parse_client_cert_local_machine_count(msg) == Some(0)
                || client_cert_failure_re().is_match(msg)
            {
                IntuneStatus::Failed
            } else {
                IntuneStatus::Unknown
            }
        }
        ImeSourceKind::DeviceHealthMonitoring | ImeSourceKind::Sensor => IntuneStatus::Failed,
        ImeSourceKind::Win32AppInventory => IntuneStatus::Success,
        ImeSourceKind::PrimaryIme | ImeSourceKind::Other => {
            if timeout_re().is_match(msg) {
                IntuneStatus::Timeout
            } else if failed_re().is_match(msg) {
                IntuneStatus::Failed
            } else if success_re().is_match(msg) {
                IntuneStatus::Success
            } else if pending_re().is_match(msg) {
                IntuneStatus::Pending
            } else {
                IntuneStatus::InProgress
            }
        }
    }
}

fn build_event_name(
    event_type: &IntuneEventType,
    guid: &Option<String>,
    msg: &str,
    source_kind: ImeSourceKind,
) -> String {
    if let Some(name) = build_source_specific_name(event_type, guid, msg, source_kind) {
        return name;
    }

    let label = match event_type {
        IntuneEventType::Win32App => "Win32 App",
        IntuneEventType::WinGetApp => "WinGet App",
        IntuneEventType::PowerShellScript => "PowerShell Script",
        IntuneEventType::Remediation => "Remediation",
        IntuneEventType::Esp => "ESP",
        IntuneEventType::SyncSession => "Sync Session",
        IntuneEventType::PolicyEvaluation => "Policy Evaluation",
        IntuneEventType::ContentDownload => "Content Download",
        IntuneEventType::Other => "Other",
    };

    if let Some(guid) = guid {
        let short = short_guid(guid);
        format!("{label} ({short})")
    } else {
        format!("{label}: {msg}")
    }
}

fn build_source_specific_name(
    event_type: &IntuneEventType,
    guid: &Option<String>,
    msg: &str,
    source_kind: ImeSourceKind,
) -> Option<String> {
    let short_guid = guid.as_deref().map(short_guid);

    match source_kind {
        ImeSourceKind::AppWorkload => {
            let phase = if appworkload_stall_re().is_match(msg) {
                "Download Stall"
            } else if appworkload_retry_re().is_match(msg) {
                "Download Retry"
            } else if appworkload_hash_re().is_match(msg) {
                "Hash Validation"
            } else if appworkload_staging_re().is_match(msg) {
                "Staging"
            } else if appworkload_install_re().is_match(msg) {
                "Install"
            } else if appworkload_download_re().is_match(msg) {
                "Download"
            } else {
                return None;
            };
            Some(match short_guid {
                Some(short) => format!("AppWorkload {phase} ({short})"),
                None => format!("AppWorkload {phase}"),
            })
        }
        ImeSourceKind::AppActionProcessor => {
            let area = if applicability_block_re().is_match(msg) || applicability_re().is_match(msg)
            {
                "Applicability"
            } else if contains_case_insensitive(msg, "requirement rule") {
                "Requirement Rule"
            } else if contains_case_insensitive(msg, "detection rule") {
                "Detection Rule"
            } else if policy_eval_re().is_match(msg) {
                "Policy Evaluation"
            } else {
                return None;
            };
            Some(match short_guid {
                Some(short) => format!("AppActionProcessor {area} ({short})"),
                None => format!("AppActionProcessor {area}"),
            })
        }
        ImeSourceKind::AgentExecutor => {
            let area = if remediation_script_re().is_match(msg)
                || *event_type == IntuneEventType::Remediation
            {
                "Remediation Script"
            } else if detection_script_re().is_match(msg) {
                "Detection Script"
            } else if timeout_re().is_match(msg) {
                "Script Timeout"
            } else {
                "PowerShell Script"
            };
            Some(match short_guid {
                Some(short) => format!("AgentExecutor {area} ({short})"),
                None => format!("AgentExecutor {area}"),
            })
        }
        ImeSourceKind::HealthScripts => {
            let area = if remediation_script_re().is_match(msg) {
                "Remediation"
            } else if detection_script_re().is_match(msg)
                || contains_case_insensitive(msg, "compliance result")
            {
                "Detection"
            } else {
                "Schedule"
            };
            Some(match short_guid {
                Some(short) => format!("HealthScripts {area} ({short})"),
                None => format!("HealthScripts {area}"),
            })
        }
        ImeSourceKind::ClientHealth => {
            if let Some((rule, status, details)) = parse_client_health_summary(msg) {
                let status_label = match status {
                    IntuneStatus::Success => "Passed",
                    IntuneStatus::Failed => "Failed",
                    IntuneStatus::Pending => "Pending",
                    IntuneStatus::InProgress => "In Progress",
                    IntuneStatus::Timeout => "Timed Out",
                    IntuneStatus::Unknown => "Unknown",
                };
                let suffix = if details.eq_ignore_ascii_case("N/A") {
                    String::new()
                } else {
                    format!(": {}", details.chars().take(40).collect::<String>())
                };
                return Some(format!("ClientHealth Rule {status_label}: {rule}{suffix}"));
            }
            if client_health_heartbeat_failure_re().is_match(msg) {
                Some("ClientHealth Heartbeat Failed".to_string())
            } else if client_health_heartbeat_success_re().is_match(msg) {
                Some("ClientHealth Heartbeat Sent".to_string())
            } else {
                None
            }
        }
        ImeSourceKind::ClientCertCheck => {
            if parse_client_cert_local_machine_count(msg) == Some(0) {
                Some("ClientCertCheck Missing MDM Certificate".to_string())
            } else if client_cert_failure_re().is_match(msg) {
                Some("ClientCertCheck Validation Failure".to_string())
            } else {
                None
            }
        }
        ImeSourceKind::DeviceHealthMonitoring => {
            parse_device_health_app_crash(msg).map(|(app_name, exception_code)| {
                format!(
                    "DeviceHealthMonitoring App Crash: {} ({})",
                    app_name, exception_code
                )
            })
        }
        ImeSourceKind::Sensor => {
            if sensor_memory_failure_re().is_match(msg) {
                Some("Sensor Hardware Readiness Memory Failure".to_string())
            } else {
                None
            }
        }
        ImeSourceKind::Win32AppInventory => {
            if win32_app_inventory_full_re().is_match(msg) {
                Some("Win32AppInventory Full Inventory".to_string())
            } else if win32_app_inventory_no_change_re().is_match(msg) {
                Some("Win32AppInventory No Delta".to_string())
            } else if let Some((add, modify, delete)) = parse_win32_app_inventory_delta(msg) {
                Some(format!(
                    "Win32AppInventory Delta (+{add} ~{modify} -{delete})"
                ))
            } else {
                None
            }
        }
        ImeSourceKind::PrimaryIme | ImeSourceKind::Other => None,
    }
}

fn parse_client_health_summary(msg: &str) -> Option<(String, IntuneStatus, String)> {
    let captures = client_health_rule_summary_re().captures(msg)?;
    let rule = captures.get(1)?.as_str().trim().to_string();
    let status = match captures.get(2)?.as_str().to_ascii_lowercase().as_str() {
        "pass" => IntuneStatus::Success,
        "fail" => IntuneStatus::Failed,
        _ => IntuneStatus::Unknown,
    };
    let details = captures.get(3)?.as_str().trim().to_string();
    Some((rule, status, details))
}

fn parse_client_cert_local_machine_count(msg: &str) -> Option<u32> {
    client_cert_local_machine_count_re()
        .captures(msg)
        .and_then(|cap| cap.get(1))
        .and_then(|value| value.as_str().parse::<u32>().ok())
}

fn parse_device_health_app_crash(msg: &str) -> Option<(String, String)> {
    let captures = device_health_app_crash_re().captures(msg)?;
    let app_name = captures.get(1)?.as_str().trim().to_string();
    let exception_code = captures.get(2)?.as_str().trim().to_string();
    Some((app_name, exception_code))
}

fn parse_win32_app_inventory_delta(msg: &str) -> Option<(u32, u32, u32)> {
    let captures = win32_app_inventory_delta_re().captures(msg)?;
    let add = captures.get(1)?.as_str().parse::<u32>().ok()?;
    let modify = captures.get(2)?.as_str().parse::<u32>().ok()?;
    let delete = captures.get(3)?.as_str().parse::<u32>().ok()?;
    Some((add, modify, delete))
}

fn short_guid(value: &str) -> &str {
    value
}

fn contains_case_insensitive(value: &str, needle: &str) -> bool {
    contains_ascii_case_insensitive(value, needle)
}

fn contains_any_ascii_case_insensitive(value: &str, needles: &[&str]) -> bool {
    needles
        .iter()
        .copied()
        .any(|needle| contains_ascii_case_insensitive(value, needle))
}

fn contains_ascii_case_insensitive(value: &str, needle: &str) -> bool {
    if needle.is_empty() {
        return true;
    }
    if needle.len() > value.len() {
        return false;
    }

    value
        .as_bytes()
        .windows(needle.len())
        .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
}

fn ends_with_ascii_case_insensitive(value: &str, suffix: &str) -> bool {
    value
        .get(value.len().saturating_sub(suffix.len())..)
        .is_some_and(|tail| tail.eq_ignore_ascii_case(suffix))
}

fn pair_events(events: &mut Vec<IntuneEvent>) {
    let mut consumed_end_indices: HashSet<usize> = HashSet::new();
    let mut open_events: HashMap<String, Vec<usize>> = HashMap::new();

    for index in 0..events.len() {
        let status = events[index].status;
        let Some(identity_key) = event_identity_key(&events[index]) else {
            continue;
        };

        if status == IntuneStatus::InProgress {
            open_events.entry(identity_key).or_default().push(index);
            continue;
        }
        if !(status == IntuneStatus::Success
            || status == IntuneStatus::Failed
            || status == IntuneStatus::Timeout)
        {
            continue;
        }

        let Some(start_index) = open_events
            .get_mut(&identity_key)
            .and_then(|indices| indices.pop())
        else {
            continue;
        };
        if consumed_end_indices.contains(&index) {
            continue;
        }

        events[start_index].end_time = events[index].start_time.clone();
        events[start_index].status = events[index].status;
        events[start_index].error_code = events[index]
            .error_code
            .clone()
            .or_else(|| events[start_index].error_code.clone());

        if let (Some(start), Some(end)) = (
            &events[start_index].start_time,
            &events[start_index].end_time,
        ) {
            events[start_index].duration_secs = estimate_duration(start, end);
        }

        consumed_end_indices.insert(index);
    }

    if consumed_end_indices.is_empty() {
        return;
    }

    let mut index = 0usize;
    events.retain(|_| {
        let keep = !consumed_end_indices.contains(&index);
        index += 1;
        keep
    });
}

fn event_identity_key(event: &IntuneEvent) -> Option<String> {
    if let Some(guid) = &event.guid {
        return Some(format!(
            "{}|{}|{}",
            event.source_file,
            event_type_identity(&event.event_type),
            guid
        ));
    }

    let normalized_name = normalize_identity_fragment(&event.name);
    if normalized_name.is_empty() {
        None
    } else {
        Some(format!(
            "{}|{}|{}",
            event.source_file,
            event_type_identity(&event.event_type),
            normalized_name
        ))
    }
}

fn event_type_identity(event_type: &IntuneEventType) -> &'static str {
    match event_type {
        IntuneEventType::Win32App => "win32",
        IntuneEventType::WinGetApp => "winget",
        IntuneEventType::PowerShellScript => "script",
        IntuneEventType::Remediation => "remediation",
        IntuneEventType::Esp => "esp",
        IntuneEventType::SyncSession => "sync",
        IntuneEventType::PolicyEvaluation => "policy",
        IntuneEventType::ContentDownload => "download",
        IntuneEventType::Other => "other",
    }
}

fn normalize_identity_fragment(value: &str) -> String {
    value
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() {
                ch.to_ascii_lowercase()
            } else {
                ' '
            }
        })
        .collect::<String>()
        .split_whitespace()
        .take(6)
        .collect::<Vec<_>>()
        .join(" ")
}

fn estimate_duration(start: &str, end: &str) -> Option<f64> {
    if let (Some(start_dt), Some(end_dt)) =
        (parse_event_timestamp(start), parse_event_timestamp(end))
    {
        return Some((end_dt - start_dt).num_milliseconds().abs() as f64 / 1000.0);
    }

    let parse_seconds = |ts: &str| -> Option<f64> {
        let time_part = ts.split_whitespace().last()?;
        let parts: Vec<&str> = time_part.split(':').collect();
        if parts.len() >= 3 {
            let h: f64 = parts[0].parse().ok()?;
            let m: f64 = parts[1].parse().ok()?;
            let s: f64 = parts[2].parse().ok()?;
            Some(h * 3600.0 + m * 60.0 + s)
        } else {
            None
        }
    };

    let start_secs = parse_seconds(start)?;
    let end_secs = parse_seconds(end)?;
    let diff = end_secs - start_secs;
    if diff >= 0.0 {
        Some(diff)
    } else {
        Some(diff + 86400.0)
    }
}

fn parse_event_timestamp(value: &str) -> Option<chrono::DateTime<chrono::Utc>> {
    if let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(value) {
        return Some(parsed.with_timezone(&chrono::Utc));
    }

    let naive = chrono::NaiveDateTime::parse_from_str(value, "%m-%d-%Y %H:%M:%S%.f").ok()?;
    Some(chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(
        naive,
        chrono::Utc,
    ))
}

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

    fn empty_registry() -> GuidRegistry {
        GuidRegistry::new()
    }

    fn line(message: &str, timestamp: &str, line_number: u32) -> ImeLine {
        ImeLine {
            line_number,
            timestamp: Some(timestamp.to_string()),
            timestamp_utc: Some(timestamp.to_string()),
            message: message.to_string(),
            component: None,
        }
    }

    #[test]
    fn extract_events_prefers_utc_normalized_timestamp() {
        let events = extract_events(
            &[ImeLine {
                line_number: 1,
                timestamp: Some("03-12-2026 11:16:42.332".to_string()),
                timestamp_utc: Some("2026-03-12T11:16:42.332Z".to_string()),
                message: "Assignment evaluation failed for app with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890".to_string(),
                component: None,
            }],
            "C:/Logs/AppActionProcessor.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(
            events[0].start_time.as_deref(),
            Some("2026-03-12T11:16:42.332Z")
        );
    }

    #[test]
    fn estimate_duration_supports_iso_timestamps() {
        assert_eq!(
            estimate_duration("2026-03-12T11:16:42.332Z", "2026-03-12T11:16:47.332Z"),
            Some(5.0)
        );
    }

    #[test]
    fn appworkload_extracts_stalled_download_events() {
        let events = extract_events(
            &[line(
                "AppWorkload download stalled with no progress for app id: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/AppWorkload.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, IntuneEventType::ContentDownload);
        assert_eq!(events[0].status, IntuneStatus::Timeout);
    }

    #[test]
    fn app_action_processor_marks_not_applicable_as_failed() {
        let events = extract_events(
            &[line(
                "Assignment evaluation found app is not applicable and will not be enforced for app with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/AppActionProcessor.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, IntuneEventType::PolicyEvaluation);
        assert_eq!(events[0].status, IntuneStatus::Failed);
    }

    #[test]
    fn agent_executor_extracts_remediation_timeout() {
        let events = extract_events(
            &[line(
                "AgentExecutor remediation script timed out for package a1b2c3d4-e5f6-7890-abcd-ef1234567890",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/AgentExecutor.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, IntuneEventType::Remediation);
        assert_eq!(events[0].status, IntuneStatus::Timeout);
    }

    #[test]
    fn agent_executor_skips_argument_parsing_noise() {
        let events = extract_events(
            &[
                line(
                    "Creating command line parser, name delimiter is - and value separator is .",
                    "01-15-2024 10:00:05.000",
                    1,
                ),
                line(
                    "Adding argument remediationScript with value C:\\Windows\\IMECache\\HealthScripts\\abc\\detect.ps1 to the named argument list.",
                    "01-15-2024 10:00:06.000",
                    2,
                ),
            ],
            "C:/Logs/AgentExecutor.log",
            &empty_registry(),
        );

        assert!(events.is_empty());
    }

    #[test]
    fn client_health_extracts_heartbeat_failure() {
        let events = extract_events(
            &[line(
                "Failed to send heartbeat report, exception = System.NullReferenceException: Object reference not set to an instance of an object.",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/ClientHealth.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, IntuneEventType::Other);
        assert_eq!(events[0].status, IntuneStatus::Failed);
        assert_eq!(events[0].name, "ClientHealth Heartbeat Failed");
    }

    #[test]
    fn client_health_ignores_passing_rule_summaries() {
        let events = extract_events(
            &[line(
                "Summary: rule Verify Intune Management Extension service exists. with ID b862e7a7-fe34-47f3-a648-edd4803f781a, result = Pass, details = N/A",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/ClientHealth.log",
            &empty_registry(),
        );

        assert!(events.is_empty());
    }

    #[test]
    fn client_cert_check_detects_missing_local_machine_certificate() {
        let events = extract_events(
            &[line(
                "MDM certs found in LocalMachine count: 0",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/ClientCertCheck.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, IntuneEventType::Other);
        assert_eq!(events[0].status, IntuneStatus::Failed);
        assert_eq!(events[0].name, "ClientCertCheck Missing MDM Certificate");
    }

    #[test]
    fn device_health_monitoring_extracts_app_crash_event() {
        let events = extract_events(
            &[line(
                "[datasensor] received application event, RecordId: 19583, 1000 , <![CDATA[<EventData xmlns=\"http://schemas.microsoft.com/win/2004/08/events/event\">\n  <Data Name=\"AppName\">SenseNdr.exe</Data>\n  <Data Name=\"ExceptionCode\">c0000409</Data>\n</EventData>]]>",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/DeviceHealthMonitoring.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, IntuneEventType::Other);
        assert_eq!(events[0].status, IntuneStatus::Failed);
        assert_eq!(
            events[0].name,
            "DeviceHealthMonitoring App Crash: SenseNdr.exe (c0000409)"
        );
    }

    #[test]
    fn sensor_extracts_memory_failure() {
        let events = extract_events(
            &[line(
                "Win32Exception occurred. Error: 0; Message: Call to GetPhysicallyInstalledSystemMemory failed.; Stacktrace:",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/Sensor.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, IntuneEventType::Other);
        assert_eq!(events[0].status, IntuneStatus::Failed);
        assert_eq!(events[0].name, "Sensor Hardware Readiness Memory Failure");
    }

    #[test]
    fn win32_app_inventory_extracts_non_zero_delta() {
        let events = extract_events(
            &[line(
                "[Win32AppInventory] Computing delta inventory...Done. Add count = 2, Modify count = 0, Delete count = 2",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/Win32AppInventory.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, IntuneEventType::Other);
        assert_eq!(events[0].status, IntuneStatus::Success);
        assert_eq!(events[0].name, "Win32AppInventory Delta (+2 ~0 -2)");
    }

    #[test]
    fn win32_app_inventory_ignores_no_user_skip_noise() {
        let events = extract_events(
            &[line(
                "[Win32AppInventory] OnAppInventoryCollecting There is no any AAD User logged in, skip this round of inventory collection.",
                "01-15-2024 10:00:05.000",
                1,
            )],
            "C:/Logs/Win32AppInventory.log",
            &empty_registry(),
        );

        assert!(events.is_empty());
    }

    #[test]
    fn paired_completion_events_are_collapsed() {
        let events = extract_events(
            &[
                line(
                    "[Win32App] Processing app with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
                    "01-15-2024 10:00:00.000",
                    1,
                ),
                line(
                    "[Win32App] Completed successfully for app with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
                    "01-15-2024 10:01:00.000",
                    2,
                ),
            ],
            "C:/Logs/IntuneManagementExtension.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].status, IntuneStatus::Success);
        assert_eq!(events[0].duration_secs, Some(60.0));
    }

    #[test]
    fn appworkload_request_payload_events_are_paired() {
        let events = extract_events(
            &[
                line(
                    r#"Starting content download RequestPayload: {\"AppId\":\"a1b2c3d4-e5f6-7890-abcd-ef1234567890\",\"ApplicationName\":\"Contoso App\"}"#,
                    "01-15-2024 10:00:00.000",
                    1,
                ),
                line(
                    r#"Download completed successfully RequestPayload: {\"AppId\":\"a1b2c3d4-e5f6-7890-abcd-ef1234567890\",\"ApplicationName\":\"Contoso App\"}"#,
                    "01-15-2024 10:00:05.000",
                    2,
                ),
            ],
            "C:/Logs/AppWorkload.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, IntuneEventType::ContentDownload);
        assert_eq!(events[0].status, IntuneStatus::Success);
        assert_eq!(
            events[0].guid.as_deref(),
            Some("a1b2c3d4-e5f6-7890-abcd-ef1234567890")
        );
        assert_eq!(events[0].duration_secs, Some(5.0));
    }

    #[test]
    fn appworkload_failed_events_include_guid_context() {
        let events = extract_events(
            &[
                line(
                    "[Win32App][ReportingManager] App with id: a1b2c3d4-e5f6-7890-abcd-ef1234567890 has been loaded.",
                    "01-15-2024 10:00:00.000",
                    10,
                ),
                line(
                    "[Win32App][V3Processor] Processing subgraph with app ids: a1b2c3d4-e5f6-7890-abcd-ef1234567890",
                    "01-15-2024 10:00:01.000",
                    11,
                ),
                line(
                    "Download failed for app id: a1b2c3d4-e5f6-7890-abcd-ef1234567890 with error code = 0x87D30067",
                    "01-15-2024 10:00:02.000",
                    12,
                ),
                line(
                    "[Win32App][V3Processor] Done processing subgraph.",
                    "01-15-2024 10:00:03.000",
                    13,
                ),
            ],
            "C:/Logs/AppWorkload.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].status, IntuneStatus::Failed);
        assert!(events[0].detail.contains("AppWorkload context:"));
        assert!(events[0].detail.contains("L10 01-15-2024 10:00:00.000"));
        assert!(events[0].detail.contains("L11 01-15-2024 10:00:01.000"));
        assert!(events[0].detail.contains("> L12 01-15-2024 10:00:02.000"));
        assert!(events[0].detail.contains("L13 01-15-2024 10:00:03.000"));
    }

    #[test]
    fn appworkload_success_events_keep_single_line_detail() {
        let message =
            "Download completed successfully for app id: a1b2c3d4-e5f6-7890-abcd-ef1234567890";
        let events = extract_events(
            &[line(message, "01-15-2024 10:00:05.000", 20)],
            "C:/Logs/AppWorkload.log",
            &empty_registry(),
        );

        assert_eq!(events.len(), 1);
        assert_eq!(events[0].status, IntuneStatus::Success);
        assert_eq!(events[0].detail, message);
    }
}