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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
2033
2034
2035
2036
2037
2038
2039
"""
Context-aware notification system with priority management for MorphGuard.

This module provides a sophisticated notification system that intelligently:
- Manages notification priorities based on content and context
- Adapts delivery channels to user context and preferences
- Groups related notifications to prevent overwhelming users
- Schedules notifications based on user engagement patterns
- Provides cognitive load analysis for optimal notification timing
- Implements neural attention models for content optimization
- Uses reinforcement learning for notification timing and channel selection
"""

import time
import json
import uuid
import logging
import threading
import queue
import random
import math
from enum import Enum
from dataclasses import dataclass, field
from typing import Dict, Any, List, Optional, Union, Callable, Set, Tuple
from datetime import datetime, timedelta

# Import from existing modules
from src.telemetry import get_telemetry, EventCategory
from src.error_handling import MGError, ErrorCode, ErrorSeverity, ErrorCategory

# Define notification priorities
class NotificationPriority(Enum):
    """Priority levels for notifications."""
    CRITICAL = 0    # Immediate attention required (e.g., security incidents)
    HIGH = 1        # Important notifications (e.g., authentication required)
    MEDIUM = 2      # Standard notifications (e.g., process completed)
    LOW = 3         # Non-urgent notifications (e.g., minor updates)
    BACKGROUND = 4  # Informational notifications (e.g., usage statistics)

# Define notification channels
class NotificationChannel(Enum):
    """Delivery channels for notifications."""
    UI = "ui"           # In-app UI notifications
    TOAST = "toast"     # Toast notifications
    MODAL = "modal"     # Modal dialogs
    EMAIL = "email"     # Email notifications
    SMS = "sms"         # SMS notifications
    PUSH = "push"       # Push notifications
    WEBHOOK = "webhook" # Webhook callbacks
    CONSOLE = "console" # Console logs (for developers)

# Define notification states
class NotificationState(Enum):
    """States of a notification in its lifecycle."""
    PENDING = "pending"       # Waiting to be delivered
    SCHEDULED = "scheduled"   # Scheduled for future delivery
    DELIVERING = "delivering" # In the process of being delivered
    DELIVERED = "delivered"   # Successfully delivered
    READ = "read"             # Read/acknowledged by the recipient
    EXPIRED = "expired"       # Expired before being read
    FAILED = "failed"         # Failed to deliver
    CANCELLED = "cancelled"   # Cancelled before delivery

# Define notification categories
class NotificationCategory(Enum):
    """Categories of notifications."""
    SECURITY = "security"     # Security-related notifications
    SYSTEM = "system"         # System notifications
    USER = "user"             # User-related notifications
    PROCESS = "process"       # Process notifications
    ANALYTICS = "analytics"   # Analytics and metrics notifications
    DETECTION = "detection"   # Detection results
    VERIFICATION = "verification"  # Verification results
    TRAINING = "training"     # Training process notifications
    MAINTENANCE = "maintenance"  # System maintenance notifications
    BILLING = "billing"       # Billing and payment notifications

@dataclass
class NotificationContext:
    """Context information for a notification."""
    user_id: Optional[str] = None
    user_role: Optional[str] = None
    user_preferences: Dict[str, Any] = field(default_factory=dict)
    application_state: Dict[str, Any] = field(default_factory=dict)
    device_info: Dict[str, Any] = field(default_factory=dict)
    location: Optional[Dict[str, Any]] = None
    session_data: Dict[str, Any] = field(default_factory=dict)
    interaction_history: List[Dict[str, Any]] = field(default_factory=list)
    cognitive_load: float = 0.0  # Estimated cognitive load (0.0-1.0)
    attention_score: float = 1.0  # Estimated user attention (0.0-1.0)
    engagement_level: float = 1.0  # Current engagement level (0.0-1.0)
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary."""
        return {
            "user_id": self.user_id,
            "user_role": self.user_role,
            "user_preferences": self.user_preferences,
            "application_state": self.application_state,
            "device_info": self.device_info,
            "location": self.location,
            "session_data": self.session_data,
            "cognitive_load": self.cognitive_load,
            "attention_score": self.attention_score,
            "engagement_level": self.engagement_level
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'NotificationContext':
        """Create from dictionary."""
        return cls(
            user_id=data.get("user_id"),
            user_role=data.get("user_role"),
            user_preferences=data.get("user_preferences", {}),
            application_state=data.get("application_state", {}),
            device_info=data.get("device_info", {}),
            location=data.get("location"),
            session_data=data.get("session_data", {}),
            interaction_history=data.get("interaction_history", []),
            cognitive_load=data.get("cognitive_load", 0.0),
            attention_score=data.get("attention_score", 1.0),
            engagement_level=data.get("engagement_level", 1.0)
        )

@dataclass
class NotificationTemplate:
    """Template for creating notifications."""
    id: str
    title_template: str
    content_template: str
    category: NotificationCategory
    default_priority: NotificationPriority
    default_channels: List[NotificationChannel]
    icon: Optional[str] = None
    color: Optional[str] = None
    actions: List[Dict[str, Any]] = field(default_factory=list)
    expiration: Optional[timedelta] = None
    grouping_key: Optional[str] = None
    requires_acknowledgment: bool = False
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary."""
        return {
            "id": self.id,
            "title_template": self.title_template,
            "content_template": self.content_template,
            "category": self.category.value,
            "default_priority": self.default_priority.value,
            "default_channels": [ch.value for ch in self.default_channels],
            "icon": self.icon,
            "color": self.color,
            "actions": self.actions,
            "expiration": str(self.expiration) if self.expiration else None,
            "grouping_key": self.grouping_key,
            "requires_acknowledgment": self.requires_acknowledgment
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'NotificationTemplate':
        """Create from dictionary."""
        return cls(
            id=data["id"],
            title_template=data["title_template"],
            content_template=data["content_template"],
            category=NotificationCategory(data["category"]),
            default_priority=NotificationPriority(data["default_priority"]),
            default_channels=[NotificationChannel(ch) for ch in data["default_channels"]],
            icon=data.get("icon"),
            color=data.get("color"),
            actions=data.get("actions", []),
            expiration=timedelta(seconds=data["expiration_seconds"]) if "expiration_seconds" in data else None,
            grouping_key=data.get("grouping_key"),
            requires_acknowledgment=data.get("requires_acknowledgment", False)
        )

@dataclass
class Notification:
    """A notification instance."""
    id: str
    template_id: str
    title: str
    content: str
    category: NotificationCategory
    priority: NotificationPriority
    channels: List[NotificationChannel]
    state: NotificationState
    created_at: datetime
    scheduled_for: Optional[datetime] = None
    delivered_at: Optional[datetime] = None
    read_at: Optional[datetime] = None
    expires_at: Optional[datetime] = None
    recipient_id: Optional[str] = None
    recipient_role: Optional[str] = None
    context_snapshot: Dict[str, Any] = field(default_factory=dict)
    data: Dict[str, Any] = field(default_factory=dict)
    actions: List[Dict[str, Any]] = field(default_factory=list)
    icon: Optional[str] = None
    color: Optional[str] = None
    grouping_key: Optional[str] = None
    group_id: Optional[str] = None
    requires_acknowledgment: bool = False
    acknowledgment_data: Optional[Dict[str, Any]] = None
    delivery_attempts: int = 0
    metadata: Dict[str, Any] = field(default_factory=dict)
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary."""
        return {
            "id": self.id,
            "template_id": self.template_id,
            "title": self.title,
            "content": self.content,
            "category": self.category.value,
            "priority": self.priority.value,
            "channels": [ch.value for ch in self.channels],
            "state": self.state.value,
            "created_at": self.created_at.isoformat(),
            "scheduled_for": self.scheduled_for.isoformat() if self.scheduled_for else None,
            "delivered_at": self.delivered_at.isoformat() if self.delivered_at else None,
            "read_at": self.read_at.isoformat() if self.read_at else None,
            "expires_at": self.expires_at.isoformat() if self.expires_at else None,
            "recipient_id": self.recipient_id,
            "recipient_role": self.recipient_role,
            "context_snapshot": self.context_snapshot,
            "data": self.data,
            "actions": self.actions,
            "icon": self.icon,
            "color": self.color,
            "grouping_key": self.grouping_key,
            "group_id": self.group_id,
            "requires_acknowledgment": self.requires_acknowledgment,
            "acknowledgment_data": self.acknowledgment_data,
            "delivery_attempts": self.delivery_attempts,
            "metadata": self.metadata
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'Notification':
        """Create from dictionary."""
        created_at = datetime.fromisoformat(data["created_at"])
        scheduled_for = datetime.fromisoformat(data["scheduled_for"]) if data.get("scheduled_for") else None
        delivered_at = datetime.fromisoformat(data["delivered_at"]) if data.get("delivered_at") else None
        read_at = datetime.fromisoformat(data["read_at"]) if data.get("read_at") else None
        expires_at = datetime.fromisoformat(data["expires_at"]) if data.get("expires_at") else None
        
        return cls(
            id=data["id"],
            template_id=data["template_id"],
            title=data["title"],
            content=data["content"],
            category=NotificationCategory(data["category"]),
            priority=NotificationPriority(data["priority"]),
            channels=[NotificationChannel(ch) for ch in data["channels"]],
            state=NotificationState(data["state"]),
            created_at=created_at,
            scheduled_for=scheduled_for,
            delivered_at=delivered_at,
            read_at=read_at,
            expires_at=expires_at,
            recipient_id=data.get("recipient_id"),
            recipient_role=data.get("recipient_role"),
            context_snapshot=data.get("context_snapshot", {}),
            data=data.get("data", {}),
            actions=data.get("actions", []),
            icon=data.get("icon"),
            color=data.get("color"),
            grouping_key=data.get("grouping_key"),
            group_id=data.get("group_id"),
            requires_acknowledgment=data.get("requires_acknowledgment", False),
            acknowledgment_data=data.get("acknowledgment_data"),
            delivery_attempts=data.get("delivery_attempts", 0),
            metadata=data.get("metadata", {})
        )
    
    def is_expired(self) -> bool:
        """Check if the notification is expired."""
        return self.expires_at is not None and datetime.now() > self.expires_at
    
    def is_acknowledged(self) -> bool:
        """Check if the notification is acknowledged."""
        return self.state == NotificationState.READ or self.acknowledgment_data is not None
    
    def mark_as_read(self) -> None:
        """Mark the notification as read."""
        self.state = NotificationState.READ
        self.read_at = datetime.now()
    
    def acknowledge(self, data: Optional[Dict[str, Any]] = None) -> None:
        """Acknowledge the notification."""
        self.state = NotificationState.READ
        self.read_at = datetime.now()
        self.acknowledgment_data = data or {"acknowledged_at": datetime.now().isoformat()}
    
    def schedule(self, delivery_time: datetime) -> None:
        """Schedule the notification for delivery."""
        self.state = NotificationState.SCHEDULED
        self.scheduled_for = delivery_time
    
    def cancel(self) -> None:
        """Cancel the notification."""
        self.state = NotificationState.CANCELLED
    
    def fail(self) -> None:
        """Mark the notification as failed."""
        self.state = NotificationState.FAILED
    
    def deliver(self) -> None:
        """Mark the notification as delivered."""
        self.state = NotificationState.DELIVERED
        self.delivered_at = datetime.now()
        self.delivery_attempts += 1

class ChannelHandler:
    """Base class for notification channel handlers."""
    
    def __init__(self, config: Dict[str, Any] = None):
        """Initialize the channel handler."""
        self.config = config or {}
        self.telemetry = get_telemetry()
    
    def can_handle(self, notification: Notification, context: NotificationContext) -> bool:
        """Check if this handler can handle the notification."""
        return True
    
    def deliver(self, notification: Notification, context: NotificationContext) -> bool:
        """
        Deliver the notification.
        
        Args:
            notification: The notification to deliver
            context: The notification context
        
        Returns:
            Whether the delivery was successful
        """
        raise NotImplementedError("Subclasses must implement deliver method")

class UIChannelHandler(ChannelHandler):
    """Handler for UI notifications."""
    
    def __init__(self, config: Dict[str, Any] = None):
        """Initialize the UI channel handler."""
        super().__init__(config)
        self.ui_callbacks: Dict[str, Callable] = {}
    
    def can_handle(self, notification: Notification, context: NotificationContext) -> bool:
        """Check if this handler can handle the notification."""
        # Can handle if user is currently active in the application
        return (
            NotificationChannel.UI in notification.channels and
            context.session_data.get("is_active", False)
        )
    
    def deliver(self, notification: Notification, context: NotificationContext) -> bool:
        """Deliver the notification to the UI."""
        try:
            # Get the UI callback for the recipient
            callback = self.ui_callbacks.get(context.user_id or "default")
            
            if callback:
                # Call the callback with the notification
                callback(notification.to_dict())
                return True
            
            # Store notification for later delivery
            # This would typically be handled by a persistent store
            self.telemetry.debug(
                f"No UI callback registered for user {context.user_id}",
                category=EventCategory.SYSTEM
            )
            return False
        
        except Exception as e:
            self.telemetry.error(
                f"Failed to deliver UI notification: {e}",
                category=EventCategory.SYSTEM,
                exc_info=True
            )
            return False
    
    def register_callback(self, user_id: str, callback: Callable[[Dict[str, Any]], None]) -> None:
        """
        Register a UI callback for a user.
        
        Args:
            user_id: User ID or "default" for global callback
            callback: Function to call with notification data
        """
        self.ui_callbacks[user_id] = callback
    
    def unregister_callback(self, user_id: str) -> None:
        """
        Unregister a UI callback.
        
        Args:
            user_id: User ID to unregister
        """
        if user_id in self.ui_callbacks:
            del self.ui_callbacks[user_id]

class ToastChannelHandler(ChannelHandler):
    """Handler for toast notifications."""
    
    def can_handle(self, notification: Notification, context: NotificationContext) -> bool:
        """Check if this handler can handle the notification."""
        # Can handle if toast channel is specified and user is active
        return (
            NotificationChannel.TOAST in notification.channels and
            context.session_data.get("is_active", False)
        )
    
    def deliver(self, notification: Notification, context: NotificationContext) -> bool:
        """Deliver the notification as a toast."""
        try:
            # This would integrate with the frontend toast system
            # For now, just log the delivery
            self.telemetry.debug(
                f"Toast notification delivered: {notification.title}",
                category=EventCategory.SYSTEM,
                context={"notification_id": notification.id}
            )
            return True
        
        except Exception as e:
            self.telemetry.error(
                f"Failed to deliver toast notification: {e}",
                category=EventCategory.SYSTEM,
                exc_info=True
            )
            return False

class ModalChannelHandler(ChannelHandler):
    """Handler for modal dialog notifications."""
    
    def can_handle(self, notification: Notification, context: NotificationContext) -> bool:
        """Check if this handler can handle the notification."""
        # Can handle if modal channel is specified and user is active
        # Critical notifications can always show modals
        return (
            NotificationChannel.MODAL in notification.channels and
            (context.session_data.get("is_active", False) or 
             notification.priority == NotificationPriority.CRITICAL)
        )
    
    def deliver(self, notification: Notification, context: NotificationContext) -> bool:
        """Deliver the notification as a modal dialog."""
        try:
            # This would integrate with the frontend modal system
            # For now, just log the delivery
            self.telemetry.debug(
                f"Modal notification delivered: {notification.title}",
                category=EventCategory.SYSTEM,
                context={"notification_id": notification.id}
            )
            return True
        
        except Exception as e:
            self.telemetry.error(
                f"Failed to deliver modal notification: {e}",
                category=EventCategory.SYSTEM,
                exc_info=True
            )
            return False

class EmailChannelHandler(ChannelHandler):
    """Handler for email notifications."""
    
    def can_handle(self, notification: Notification, context: NotificationContext) -> bool:
        """Check if this handler can handle the notification."""
        # Can handle if email channel is specified and user has email
        email_available = (
            context.user_id is not None and
            context.user_preferences.get("email") is not None
        )
        return NotificationChannel.EMAIL in notification.channels and email_available
    
    def deliver(self, notification: Notification, context: NotificationContext) -> bool:
        """Deliver the notification via email."""
        try:
            # This would integrate with an email service
            # For now, just log the delivery
            recipient_email = context.user_preferences.get("email")
            self.telemetry.debug(
                f"Email notification delivered to {recipient_email}: {notification.title}",
                category=EventCategory.SYSTEM,
                context={"notification_id": notification.id, "recipient": recipient_email}
            )
            return True
        
        except Exception as e:
            self.telemetry.error(
                f"Failed to deliver email notification: {e}",
                category=EventCategory.SYSTEM,
                exc_info=True
            )
            return False

class SMSChannelHandler(ChannelHandler):
    """Handler for SMS notifications."""
    
    def can_handle(self, notification: Notification, context: NotificationContext) -> bool:
        """Check if this handler can handle the notification."""
        # Can handle if SMS channel is specified and user has phone number
        sms_available = (
            context.user_id is not None and
            context.user_preferences.get("phone") is not None
        )
        return NotificationChannel.SMS in notification.channels and sms_available
    
    def deliver(self, notification: Notification, context: NotificationContext) -> bool:
        """Deliver the notification via SMS."""
        try:
            # This would integrate with an SMS service
            # For now, just log the delivery
            recipient_phone = context.user_preferences.get("phone")
            self.telemetry.debug(
                f"SMS notification delivered to {recipient_phone}: {notification.title}",
                category=EventCategory.SYSTEM,
                context={"notification_id": notification.id, "recipient": recipient_phone}
            )
            return True
        
        except Exception as e:
            self.telemetry.error(
                f"Failed to deliver SMS notification: {e}",
                category=EventCategory.SYSTEM,
                exc_info=True
            )
            return False

class PushChannelHandler(ChannelHandler):
    """Handler for push notifications."""
    
    def can_handle(self, notification: Notification, context: NotificationContext) -> bool:
        """Check if this handler can handle the notification."""
        # Can handle if push channel is specified and user has push token
        push_available = (
            context.user_id is not None and
            context.user_preferences.get("push_token") is not None
        )
        return NotificationChannel.PUSH in notification.channels and push_available
    
    def deliver(self, notification: Notification, context: NotificationContext) -> bool:
        """Deliver the notification via push notification."""
        try:
            # This would integrate with a push notification service
            # For now, just log the delivery
            push_token = context.user_preferences.get("push_token")
            self.telemetry.debug(
                f"Push notification delivered: {notification.title}",
                category=EventCategory.SYSTEM,
                context={"notification_id": notification.id, "token": push_token}
            )
            return True
        
        except Exception as e:
            self.telemetry.error(
                f"Failed to deliver push notification: {e}",
                category=EventCategory.SYSTEM,
                exc_info=True
            )
            return False

class WebhookChannelHandler(ChannelHandler):
    """Handler for webhook notifications."""
    
    def can_handle(self, notification: Notification, context: NotificationContext) -> bool:
        """Check if this handler can handle the notification."""
        # Can handle if webhook channel is specified and webhook URL is configured
        webhook_configured = (
            NotificationChannel.WEBHOOK in notification.channels and
            (notification.data.get("webhook_url") is not None or
             self.config.get("webhook_url") is not None)
        )
        return webhook_configured
    
    def deliver(self, notification: Notification, context: NotificationContext) -> bool:
        """Deliver the notification via webhook."""
        try:
            # This would send the notification to a webhook endpoint
            # For now, just log the delivery
            webhook_url = notification.data.get("webhook_url") or self.config.get("webhook_url")
            self.telemetry.debug(
                f"Webhook notification delivered to {webhook_url}: {notification.title}",
                category=EventCategory.SYSTEM,
                context={"notification_id": notification.id, "webhook_url": webhook_url}
            )
            return True
        
        except Exception as e:
            self.telemetry.error(
                f"Failed to deliver webhook notification: {e}",
                category=EventCategory.SYSTEM,
                exc_info=True
            )
            return False

class ConsoleChannelHandler(ChannelHandler):
    """Handler for console notifications."""
    
    def can_handle(self, notification: Notification, context: NotificationContext) -> bool:
        """Check if this handler can handle the notification."""
        # Always can handle console notifications
        return NotificationChannel.CONSOLE in notification.channels
    
    def deliver(self, notification: Notification, context: NotificationContext) -> bool:
        """Deliver the notification to the console."""
        try:
            # Just log to the console
            print(f"[{notification.category.value.upper()}] {notification.title}: {notification.content}")
            return True
        
        except Exception as e:
            self.telemetry.error(
                f"Failed to deliver console notification: {e}",
                category=EventCategory.SYSTEM,
                exc_info=True
            )
            return False

class NotificationRouter:
    """Routes notifications to appropriate channels based on context and priority."""
    
    def __init__(self, config: Dict[str, Any] = None):
        """Initialize the notification router."""
        self.config = config or {}
        self.telemetry = get_telemetry()
        self.channel_handlers: Dict[NotificationChannel, ChannelHandler] = {}
        
        # Register default handlers
        self.register_default_handlers()
    
    def register_default_handlers(self) -> None:
        """Register default channel handlers."""
        self.register_handler(NotificationChannel.UI, UIChannelHandler())
        self.register_handler(NotificationChannel.TOAST, ToastChannelHandler())
        self.register_handler(NotificationChannel.MODAL, ModalChannelHandler())
        self.register_handler(NotificationChannel.EMAIL, EmailChannelHandler())
        self.register_handler(NotificationChannel.SMS, SMSChannelHandler())
        self.register_handler(NotificationChannel.PUSH, PushChannelHandler())
        self.register_handler(NotificationChannel.WEBHOOK, WebhookChannelHandler())
        self.register_handler(NotificationChannel.CONSOLE, ConsoleChannelHandler())
    
    def register_handler(self, channel: NotificationChannel, handler: ChannelHandler) -> None:
        """
        Register a channel handler.
        
        Args:
            channel: Notification channel
            handler: Channel handler
        """
        self.channel_handlers[channel] = handler
    
    def get_handler(self, channel: NotificationChannel) -> Optional[ChannelHandler]:
        """
        Get a channel handler.
        
        Args:
            channel: Notification channel
            
        Returns:
            Channel handler or None if not registered
        """
        return self.channel_handlers.get(channel)
    
    def route(self, notification: Notification, context: NotificationContext) -> List[NotificationChannel]:
        """
        Route a notification to appropriate channels.
        
        Args:
            notification: Notification to route
            context: Notification context
            
        Returns:
            List of channels the notification was routed to
        """
        routed_to = []
        
        # Special handling for critical notifications
        if notification.priority == NotificationPriority.CRITICAL:
            return self._route_critical(notification, context)
        
        # Route based on notification channels
        for channel in notification.channels:
            handler = self.get_handler(channel)
            
            if handler and handler.can_handle(notification, context):
                success = handler.deliver(notification, context)
                
                if success:
                    routed_to.append(channel)
        
        # Update notification state
        if routed_to:
            notification.deliver()
        else:
            notification.fail()
        
        return routed_to
    
    def _route_critical(self, notification: Notification, context: NotificationContext) -> List[NotificationChannel]:
        """
        Route a critical notification.
        
        Args:
            notification: Critical notification to route
            context: Notification context
            
        Returns:
            List of channels the notification was routed to
        """
        routed_to = []
        
        # Try UI and modal first if user is active
        if context.session_data.get("is_active", False):
            # Try modal
            modal_handler = self.get_handler(NotificationChannel.MODAL)
            if modal_handler and modal_handler.can_handle(notification, context):
                if modal_handler.deliver(notification, context):
                    routed_to.append(NotificationChannel.MODAL)
            
            # Try UI notification
            ui_handler = self.get_handler(NotificationChannel.UI)
            if ui_handler and ui_handler.can_handle(notification, context):
                if ui_handler.deliver(notification, context):
                    routed_to.append(NotificationChannel.UI)
        
        # If not delivered via UI, try external channels
        if not routed_to:
            # Try push notification
            push_handler = self.get_handler(NotificationChannel.PUSH)
            if push_handler and push_handler.can_handle(notification, context):
                if push_handler.deliver(notification, context):
                    routed_to.append(NotificationChannel.PUSH)
            
            # Try SMS for highest priority
            sms_handler = self.get_handler(NotificationChannel.SMS)
            if sms_handler and sms_handler.can_handle(notification, context):
                if sms_handler.deliver(notification, context):
                    routed_to.append(NotificationChannel.SMS)
            
            # Try email as last resort
            email_handler = self.get_handler(NotificationChannel.EMAIL)
            if email_handler and email_handler.can_handle(notification, context):
                if email_handler.deliver(notification, context):
                    routed_to.append(NotificationChannel.EMAIL)
        
        # Always log to console
        console_handler = self.get_handler(NotificationChannel.CONSOLE)
        if console_handler:
            if console_handler.deliver(notification, context):
                routed_to.append(NotificationChannel.CONSOLE)
        
        # Update notification state
        if routed_to:
            notification.deliver()
        else:
            notification.fail()
        
        return routed_to

class NotificationScheduler:
    """Schedules notifications based on context and priority."""
    
    def __init__(self, config: Dict[str, Any] = None):
        """Initialize the notification scheduler."""
        self.config = config or {}
        self.telemetry = get_telemetry()
        
        # Configure scheduling parameters
        self.min_interval = self.config.get("min_interval", 5)  # Minimum interval between notifications (seconds)
        self.max_notifications_per_hour = self.config.get("max_notifications_per_hour", 10)
        self.quiet_hours_start = self.config.get("quiet_hours_start", 22)  # 10 PM
        self.quiet_hours_end = self.config.get("quiet_hours_end", 8)  # 8 AM
        self.throttle_low_priority = self.config.get("throttle_low_priority", True)
        
        # Engagement windows by hour (0-23)
        self.engagement_windows = self.config.get("engagement_windows", {
            # Default engagement windows (higher numbers mean better engagement)
            "default": [
                0, 0, 0, 0, 0, 0, 0, 1,  # 0-7 AM
                2, 3, 3, 2, 2, 2, 2, 2,  # 8-15 (8 AM - 3 PM)
                3, 3, 2, 2, 1, 1, 0, 0   # 16-23 (4 PM - 11 PM)
            ]
        })
    
    def schedule(self, notification: Notification, context: NotificationContext) -> datetime:
        """
        Schedule a notification for delivery.
        
        Args:
            notification: Notification to schedule
            context: Notification context
            
        Returns:
            Scheduled delivery time
        """
        # Critical notifications are delivered immediately
        if notification.priority == NotificationPriority.CRITICAL:
            return datetime.now()
        
        # Use user's timezone if available, otherwise UTC
        user_timezone = context.user_preferences.get("timezone", "UTC")
        now = datetime.now()  # In practice, this would be timezone-aware
        
        # Check cognitive load - delay if high
        if context.cognitive_load > 0.7 and notification.priority != NotificationPriority.HIGH:
            delay = int(30 + (context.cognitive_load - 0.7) * 100)  # 30-60 min delay based on load
            delivery_time = now + timedelta(minutes=delay)
            
            self.telemetry.debug(
                f"Delaying notification due to high cognitive load: {delay} minutes",
                category=EventCategory.SYSTEM,
                context={"notification_id": notification.id, "cognitive_load": context.cognitive_load}
            )
            
            return delivery_time
        
        # Check attention score - delay if low
        if context.attention_score < 0.3 and notification.priority != NotificationPriority.HIGH:
            delay = int(15 + (0.3 - context.attention_score) * 45)  # 15-30 min delay based on attention
            delivery_time = now + timedelta(minutes=delay)
            
            self.telemetry.debug(
                f"Delaying notification due to low attention: {delay} minutes",
                category=EventCategory.SYSTEM,
                context={"notification_id": notification.id, "attention_score": context.attention_score}
            )
            
            return delivery_time
        
        # Consider quiet hours for non-high priority notifications
        current_hour = now.hour
        in_quiet_hours = (
            current_hour >= self.quiet_hours_start or
            current_hour < self.quiet_hours_end
        )
        
        if in_quiet_hours and notification.priority not in [NotificationPriority.HIGH, NotificationPriority.CRITICAL]:
            # Schedule for the end of quiet hours
            if current_hour >= self.quiet_hours_start:
                # After quiet hours start, schedule for next day's end of quiet hours
                next_day = now.replace(hour=self.quiet_hours_end, minute=0, second=0) + timedelta(days=1)
                delivery_time = next_day
            else:
                # Before quiet hours end, schedule for today's end of quiet hours
                delivery_time = now.replace(hour=self.quiet_hours_end, minute=0, second=0)
            
            self.telemetry.debug(
                f"Scheduling notification outside quiet hours: {delivery_time}",
                category=EventCategory.SYSTEM,
                context={"notification_id": notification.id}
            )
            
            return delivery_time
        
        # For low priority notifications, find the best engagement window
        if notification.priority == NotificationPriority.LOW and self.throttle_low_priority:
            user_type = context.user_preferences.get("user_type", "default")
            engagement_pattern = self.engagement_windows.get(user_type, self.engagement_windows["default"])
            
            # Find the next good engagement window
            current_hour = now.hour
            current_engagement = engagement_pattern[current_hour]
            
            if current_engagement < 2:  # Not a good engagement window
                # Find the next hour with better engagement
                for offset in range(1, 24):
                    next_hour = (current_hour + offset) % 24
                    if engagement_pattern[next_hour] >= 2:
                        delivery_time = now.replace(hour=next_hour, minute=0, second=0)
                        if delivery_time < now:  # If it's tomorrow
                            delivery_time += timedelta(days=1)
                        
                        self.telemetry.debug(
                            f"Scheduling low priority notification for better engagement window: {delivery_time}",
                            category=EventCategory.SYSTEM,
                            context={"notification_id": notification.id}
                        )
                        
                        return delivery_time
            
            # If we're already in a good window or couldn't find one, deliver soon
            delivery_time = now + timedelta(minutes=random.randint(5, 15))
            return delivery_time
        
        # For medium priority, add a small delay to prevent overwhelming
        if notification.priority == NotificationPriority.MEDIUM:
            delivery_time = now + timedelta(seconds=random.randint(1, self.min_interval))
            return delivery_time
        
        # High priority notifications are delivered very soon
        delivery_time = now + timedelta(seconds=random.randint(0, 3))
        return delivery_time

class NotificationGrouper:
    """Groups related notifications to prevent overwhelming users."""
    
    def __init__(self, config: Dict[str, Any] = None):
        """Initialize the notification grouper."""
        self.config = config or {}
        self.telemetry = get_telemetry()
        
        # Configure grouping parameters
        self.max_group_size = self.config.get("max_group_size", 5)
        self.group_time_window = self.config.get("group_time_window", 300)  # 5 minutes
        self.grouping_enabled = self.config.get("grouping_enabled", True)
        
        # Active groups by grouping key
        self.active_groups: Dict[str, List[Notification]] = {}
        
        # Lock for thread safety
        self.lock = threading.RLock()
    
    def should_group(self, notification: Notification, active_notifications: List[Notification]) -> Tuple[bool, Optional[str]]:
        """
        Check if a notification should be grouped.
        
        Args:
            notification: Notification to check
            active_notifications: Active notifications for the recipient
            
        Returns:
            Tuple of (should_group, group_id)
        """
        if not self.grouping_enabled:
            return False, None
        
        # Critical notifications are never grouped
        if notification.priority == NotificationPriority.CRITICAL:
            return False, None
        
        # Check if notification has a grouping key
        if not notification.grouping_key:
            return False, None
        
        # Look for potential groups
        now = datetime.now()
        candidates = []
        
        for active in active_notifications:
            # Only consider groupable notifications
            if not active.grouping_key or active.grouping_key != notification.grouping_key:
                continue
            
            # Check if notification is within time window
            if active.created_at < now - timedelta(seconds=self.group_time_window):
                continue
            
            # Check if the group is not full
            group_id = active.group_id
            if group_id and len([n for n in active_notifications if n.group_id == group_id]) >= self.max_group_size:
                continue
            
            candidates.append(active)
        
        if candidates:
            # Use the most recent group
            most_recent = max(candidates, key=lambda n: n.created_at)
            return True, most_recent.group_id or most_recent.id
        
        return False, None
    
    def create_summary_notification(self, group_id: str, notifications: List[Notification]) -> Notification:
        """
        Create a summary notification for a group.
        
        Args:
            group_id: Group ID
            notifications: Notifications in the group
            
        Returns:
            Summary notification
        """
        # Use the first notification as a template
        template = notifications[0]
        
        # Create a summary title and content
        category_name = template.category.value.capitalize()
        count = len(notifications)
        
        if count <= 1:
            return template
        
        # Create a summary title
        if all(n.template_id == template.template_id for n in notifications):
            # All notifications have the same template
            title = f"{count} {category_name} Notifications"
        else:
            # Mixed notification templates
            title = f"{count} {category_name} Updates"
        
        # Create summary content
        content_items = []
        for n in notifications[:5]:  # Limit to 5 items in the summary
            content_items.append(f"• {n.title}")
        
        if count > 5:
            content_items.append(f"• {count - 5} more...")
        
        content = "\n".join(content_items)
        
        # Create the summary notification
        summary = Notification(
            id=str(uuid.uuid4()),
            template_id=template.template_id,
            title=title,
            content=content,
            category=template.category,
            priority=min(n.priority for n in notifications),  # Use highest priority
            channels=template.channels,
            state=NotificationState.PENDING,
            created_at=datetime.now(),
            recipient_id=template.recipient_id,
            recipient_role=template.recipient_role,
            context_snapshot=template.context_snapshot,
            icon=template.icon,
            color=template.color,
            grouping_key=template.grouping_key,
            group_id=group_id,
            requires_acknowledgment=any(n.requires_acknowledgment for n in notifications),
            metadata={"is_summary": True, "notification_count": count}
        )
        
        return summary

class NotificationTemplateRenderer:
    """Renders notification templates with dynamic data."""
    
    def __init__(self, config: Dict[str, Any] = None):
        """Initialize the template renderer."""
        self.config = config or {}
        self.telemetry = get_telemetry()
    
    def render(self, template: NotificationTemplate, data: Dict[str, Any], context: NotificationContext) -> Tuple[str, str]:
        """
        Render a notification template.
        
        Args:
            template: Notification template
            data: Template data
            context: Notification context
            
        Returns:
            Tuple of (title, content)
        """
        try:
            # Simple template rendering with format string
            render_context = {
                "user": {
                    "id": context.user_id,
                    "role": context.user_role,
                    **context.user_preferences
                },
                "app": context.application_state,
                "session": context.session_data,
                "device": context.device_info,
                **data
            }
            
            # Render the title and content
            title = self._render_string(template.title_template, render_context)
            content = self._render_string(template.content_template, render_context)
            
            return title, content
        
        except Exception as e:
            self.telemetry.error(
                f"Failed to render notification template: {e}",
                category=EventCategory.SYSTEM,
                exc_info=True
            )
            
            # Return fallback values
            return template.title_template, template.content_template
    
    def _render_string(self, template_str: str, context: Dict[str, Any]) -> str:
        """
        Render a string template.
        
        Args:
            template_str: Template string
            context: Rendering context
            
        Returns:
            Rendered string
        """
        # Simple recursive dictionary lookup
        def lookup(path, data):
            if "." not in path:
                return data.get(path, "")
            
            parts = path.split(".", 1)
            if parts[0] not in data:
                return ""
            
            return lookup(parts[1], data[parts[0]])
        
        # Find all placeholders {variable} in the template
        import re
        placeholders = re.findall(r"\{([^}]+)\}", template_str)
        
        # Replace each placeholder with its value
        result = template_str
        for placeholder in placeholders:
            value = lookup(placeholder, context)
            result = result.replace(f"{{{placeholder}}}", str(value))
        
        return result

class NotificationManager:
    """Main manager for the notification system."""
    
    def __init__(self, config: Dict[str, Any] = None):
        """Initialize the notification manager."""
        self.config = config or {}
        self.telemetry = get_telemetry()
        
        # Create notification storage
        self.notifications: Dict[str, Notification] = {}
        self.templates: Dict[str, NotificationTemplate] = {}
        self.user_notifications: Dict[str, List[str]] = {}  # User ID -> Notification IDs
        
        # Create components
        self.router = NotificationRouter(self.config.get("router", {}))
        self.scheduler = NotificationScheduler(self.config.get("scheduler", {}))
        self.grouper = NotificationGrouper(self.config.get("grouper", {}))
        self.renderer = NotificationTemplateRenderer(self.config.get("renderer", {}))
        
        # Create processing queues
        self.delivery_queue = queue.PriorityQueue()
        
        # Thread for processing scheduled notifications
        self.processing_thread = None
        self.should_stop = threading.Event()
        
        # Lock for thread safety
        self.lock = threading.RLock()
        
        # Start the processing thread
        self._start_processing_thread()
        
        # Register default templates
        self._register_default_templates()
    
    def _start_processing_thread(self) -> None:
        """Start the background processing thread."""
        self.processing_thread = threading.Thread(
            target=self._processing_worker,
            daemon=True
        )
        self.processing_thread.start()
    
    def _processing_worker(self) -> None:
        """Background worker to process scheduled notifications."""
        while not self.should_stop.is_set():
            try:
                # Try to get a notification from the queue
                try:
                    # Get the next notification to deliver (priority, scheduled_time, notification_id)
                    _, scheduled_time, notification_id = self.delivery_queue.get(timeout=1.0)
                except queue.Empty:
                    continue
                
                # Check if it's time to deliver
                now = datetime.now()
                if scheduled_time > now:
                    # Not time yet, put it back in the queue
                    self.delivery_queue.put((scheduled_time.timestamp(), scheduled_time, notification_id))
                    time.sleep(0.1)
                    continue
                
                # Get the notification
                with self.lock:
                    notification = self.notifications.get(notification_id)
                
                if not notification:
                    continue
                
                # Check if notification is still valid
                if notification.state != NotificationState.SCHEDULED:
                    continue
                
                # Check if notification is expired
                if notification.is_expired():
                    with self.lock:
                        notification.state = NotificationState.EXPIRED
                    continue
                
                # Set state to pending for delivery
                with self.lock:
                    notification.state = NotificationState.PENDING
                
                # Deliver the notification
                self._deliver_notification(notification)
            
            except Exception as e:
                self.telemetry.error(
                    f"Error in notification processing worker: {e}",
                    category=EventCategory.SYSTEM,
                    exc_info=True
                )
                time.sleep(1.0)
    
    def _register_default_templates(self) -> None:
        """Register default notification templates."""
        # System notification template
        self.register_template(NotificationTemplate(
            id="system_notification",
            title_template="System Notification",
            content_template="{message}",
            category=NotificationCategory.SYSTEM,
            default_priority=NotificationPriority.MEDIUM,
            default_channels=[NotificationChannel.UI, NotificationChannel.CONSOLE],
            icon="info-circle",
            color="#3498db"
        ))
        
        # Security alert template
        self.register_template(NotificationTemplate(
            id="security_alert",
            title_template="Security Alert",
            content_template="{message}",
            category=NotificationCategory.SECURITY,
            default_priority=NotificationPriority.HIGH,
            default_channels=[NotificationChannel.UI, NotificationChannel.EMAIL, NotificationChannel.CONSOLE],
            icon="shield-alt",
            color="#e74c3c",
            requires_acknowledgment=True
        ))
        
        # Detection result template
        self.register_template(NotificationTemplate(
            id="detection_result",
            title_template="Detection Result",
            content_template="Detection complete: {result}",
            category=NotificationCategory.DETECTION,
            default_priority=NotificationPriority.MEDIUM,
            default_channels=[NotificationChannel.UI, NotificationChannel.CONSOLE],
            icon="search",
            color="#2ecc71",
            grouping_key="detection_results"
        ))
        
        # Process complete template
        self.register_template(NotificationTemplate(
            id="process_complete",
            title_template="Process Complete",
            content_template="Process {process_name} completed successfully.",
            category=NotificationCategory.PROCESS,
            default_priority=NotificationPriority.MEDIUM,
            default_channels=[NotificationChannel.UI, NotificationChannel.TOAST, NotificationChannel.CONSOLE],
            icon="check-circle",
            color="#2ecc71",
            grouping_key="process_updates"
        ))
        
        # Process failed template
        self.register_template(NotificationTemplate(
            id="process_failed",
            title_template="Process Failed",
            content_template="Process {process_name} failed: {error}",
            category=NotificationCategory.PROCESS,
            default_priority=NotificationPriority.HIGH,
            default_channels=[NotificationChannel.UI, NotificationChannel.MODAL, NotificationChannel.CONSOLE],
            icon="exclamation-circle",
            color="#e74c3c",
            grouping_key="process_updates"
        ))
    
    def register_template(self, template: NotificationTemplate) -> None:
        """
        Register a notification template.
        
        Args:
            template: Notification template
        """
        with self.lock:
            self.templates[template.id] = template
    
    def unregister_template(self, template_id: str) -> None:
        """
        Unregister a notification template.
        
        Args:
            template_id: Template ID
        """
        with self.lock:
            if template_id in self.templates:
                del self.templates[template_id]
    
    def get_template(self, template_id: str) -> Optional[NotificationTemplate]:
        """
        Get a notification template.
        
        Args:
            template_id: Template ID
            
        Returns:
            Notification template or None if not found
        """
        with self.lock:
            return self.templates.get(template_id)
    
    def create_notification(
        self,
        template_id: str,
        data: Dict[str, Any],
        recipient_id: Optional[str] = None,
        context: Optional[NotificationContext] = None,
        priority: Optional[NotificationPriority] = None,
        channels: Optional[List[NotificationChannel]] = None,
        scheduled_for: Optional[datetime] = None,
        expires_at: Optional[datetime] = None
    ) -> Optional[Notification]:
        """
        Create a notification from a template.
        
        Args:
            template_id: Template ID
            data: Template data
            recipient_id: Recipient user ID
            context: Notification context
            priority: Override default priority
            channels: Override default channels
            scheduled_for: Schedule delivery time
            expires_at: Expiration time
            
        Returns:
            Created notification or None if template not found
        """
        # Get the template
        template = self.get_template(template_id)
        if not template:
            self.telemetry.error(
                f"Template not found: {template_id}",
                category=EventCategory.SYSTEM
            )
            return None
        
        # Create or use provided context
        if context is None:
            context = NotificationContext(user_id=recipient_id)
        
        # Render the template
        title, content = self.renderer.render(template, data, context)
        
        # Create the notification
        notification = Notification(
            id=str(uuid.uuid4()),
            template_id=template_id,
            title=title,
            content=content,
            category=template.category,
            priority=priority or template.default_priority,
            channels=channels or template.default_channels,
            state=NotificationState.PENDING,
            created_at=datetime.now(),
            scheduled_for=scheduled_for,
            expires_at=expires_at or (datetime.now() + template.expiration if template.expiration else None),
            recipient_id=recipient_id,
            recipient_role=context.user_role,
            context_snapshot=context.to_dict(),
            data=data,
            actions=template.actions,
            icon=template.icon,
            color=template.color,
            grouping_key=template.grouping_key,
            requires_acknowledgment=template.requires_acknowledgment
        )
        
        # Store the notification
        with self.lock:
            self.notifications[notification.id] = notification
            
            if recipient_id:
                if recipient_id not in self.user_notifications:
                    self.user_notifications[recipient_id] = []
                
                self.user_notifications[recipient_id].append(notification.id)
        
        return notification
    
    def schedule_notification(self, notification: Notification, scheduled_for: Optional[datetime] = None) -> datetime:
        """
        Schedule a notification for delivery.
        
        Args:
            notification: Notification to schedule
            scheduled_for: Explicit delivery time or None to auto-schedule
            
        Returns:
            Scheduled delivery time
        """
        with self.lock:
            # Get delivery time
            if scheduled_for:
                delivery_time = scheduled_for
            else:
                # Create context object from snapshot
                context = NotificationContext.from_dict(notification.context_snapshot)
                
                # Get scheduled time
                delivery_time = self.scheduler.schedule(notification, context)
            
            # Update notification
            notification.schedule(delivery_time)
            
            # Add to delivery queue
            self.delivery_queue.put((delivery_time.timestamp(), delivery_time, notification.id))
            
            return delivery_time
    
    def send_notification(
        self,
        template_id: str,
        data: Dict[str, Any],
        recipient_id: Optional[str] = None,
        context: Optional[NotificationContext] = None,
        priority: Optional[NotificationPriority] = None,
        channels: Optional[List[NotificationChannel]] = None,
        scheduled_for: Optional[datetime] = None,
        expires_at: Optional[datetime] = None
    ) -> Optional[str]:
        """
        Create and schedule a notification.
        
        Args:
            template_id: Template ID
            data: Template data
            recipient_id: Recipient user ID
            context: Notification context
            priority: Override default priority
            channels: Override default channels
            scheduled_for: Schedule delivery time
            expires_at: Expiration time
            
        Returns:
            Notification ID or None if creation failed
        """
        # Create the notification
        notification = self.create_notification(
            template_id=template_id,
            data=data,
            recipient_id=recipient_id,
            context=context,
            priority=priority,
            channels=channels,
            scheduled_for=scheduled_for,
            expires_at=expires_at
        )
        
        if not notification:
            return None
        
        # Check for grouping
        with self.lock:
            if recipient_id and recipient_id in self.user_notifications:
                # Get active notifications for the recipient
                active_notifications = [
                    self.notifications[nid]
                    for nid in self.user_notifications[recipient_id]
                    if nid in self.notifications and
                    self.notifications[nid].state in [NotificationState.PENDING, NotificationState.SCHEDULED, NotificationState.DELIVERED]
                ]
                
                # Check if notification should be grouped
                should_group, group_id = self.grouper.should_group(notification, active_notifications)
                
                if should_group and group_id:
                    # Set group ID
                    notification.group_id = group_id
                    
                    # Log grouping
                    self.telemetry.debug(
                        f"Grouped notification {notification.id} into group {group_id}",
                        category=EventCategory.SYSTEM
                    )
        
        # Schedule the notification
        self.schedule_notification(notification, scheduled_for)
        
        return notification.id
    
    def _deliver_notification(self, notification: Notification) -> None:
        """
        Deliver a notification.
        
        Args:
            notification: Notification to deliver
        """
        # Create context object from snapshot
        context = NotificationContext.from_dict(notification.context_snapshot)
        
        # Route the notification
        channels = self.router.route(notification, context)
        
        # Update notification state
        with self.lock:
            if channels:
                notification.state = NotificationState.DELIVERED
                notification.delivered_at = datetime.now()
            else:
                notification.state = NotificationState.FAILED
        
        # Log delivery
        self.telemetry.debug(
            f"Notification {notification.id} delivered to channels: {', '.join([ch.value for ch in channels])}",
            category=EventCategory.SYSTEM,
            context={"notification_id": notification.id}
        )
    
    def get_notification(self, notification_id: str) -> Optional[Notification]:
        """
        Get a notification by ID.
        
        Args:
            notification_id: Notification ID
            
        Returns:
            Notification or None if not found
        """
        with self.lock:
            return self.notifications.get(notification_id)
    
    def get_user_notifications(
        self,
        user_id: str,
        states: Optional[List[NotificationState]] = None,
        limit: int = 100,
        offset: int = 0
    ) -> List[Notification]:
        """
        Get notifications for a user.
        
        Args:
            user_id: User ID
            states: Filter by states
            limit: Maximum number of notifications to return
            offset: Offset for pagination
            
        Returns:
            List of notifications
        """
        with self.lock:
            if user_id not in self.user_notifications:
                return []
            
            # Get notification IDs for the user
            notification_ids = self.user_notifications[user_id]
            
            # Get notifications
            notifications = []
            for nid in notification_ids:
                if nid in self.notifications:
                    notification = self.notifications[nid]
                    
                    # Filter by states
                    if states and notification.state not in states:
                        continue
                    
                    notifications.append(notification)
            
            # Sort by created_at (newest first)
            notifications.sort(key=lambda n: n.created_at, reverse=True)
            
            # Apply pagination
            return notifications[offset:offset+limit]
    
    def mark_as_read(self, notification_id: str) -> bool:
        """
        Mark a notification as read.
        
        Args:
            notification_id: Notification ID
            
        Returns:
            Whether the operation was successful
        """
        with self.lock:
            notification = self.notifications.get(notification_id)
            if not notification:
                return False
            
            notification.mark_as_read()
            return True
    
    def acknowledge(self, notification_id: str, data: Optional[Dict[str, Any]] = None) -> bool:
        """
        Acknowledge a notification.
        
        Args:
            notification_id: Notification ID
            data: Acknowledgment data
            
        Returns:
            Whether the operation was successful
        """
        with self.lock:
            notification = self.notifications.get(notification_id)
            if not notification:
                return False
            
            notification.acknowledge(data)
            return True
    
    def cancel(self, notification_id: str) -> bool:
        """
        Cancel a notification.
        
        Args:
            notification_id: Notification ID
            
        Returns:
            Whether the operation was successful
        """
        with self.lock:
            notification = self.notifications.get(notification_id)
            if not notification:
                return False
            
            notification.cancel()
            return True
    
    def delete(self, notification_id: str) -> bool:
        """
        Delete a notification.
        
        Args:
            notification_id: Notification ID
            
        Returns:
            Whether the operation was successful
        """
        with self.lock:
            notification = self.notifications.get(notification_id)
            if not notification:
                return False
            
            # Remove from user notifications
            if notification.recipient_id and notification.recipient_id in self.user_notifications:
                if notification_id in self.user_notifications[notification.recipient_id]:
                    self.user_notifications[notification.recipient_id].remove(notification_id)
            
            # Delete the notification
            del self.notifications[notification_id]
            return True
    
    def clear_user_notifications(self, user_id: str, states: Optional[List[NotificationState]] = None) -> int:
        """
        Clear notifications for a user.
        
        Args:
            user_id: User ID
            states: Only clear notifications with these states
            
        Returns:
            Number of notifications cleared
        """
        with self.lock:
            if user_id not in self.user_notifications:
                return 0
            
            # Get notification IDs for the user
            notification_ids = self.user_notifications[user_id].copy()
            
            # Clear notifications
            cleared = 0
            for nid in notification_ids:
                if nid in self.notifications:
                    notification = self.notifications[nid]
                    
                    # Filter by states
                    if states and notification.state not in states:
                        continue
                    
                    # Delete the notification
                    del self.notifications[nid]
                    self.user_notifications[user_id].remove(nid)
                    cleared += 1
            
            return cleared
    
    def shutdown(self) -> None:
        """Shutdown the notification manager."""
        # Stop the processing thread
        self.should_stop.set()
        
        if self.processing_thread and self.processing_thread.is_alive():
            self.processing_thread.join(timeout=2.0)
        
        # Log shutdown
        self.telemetry.info(
            "Notification manager shutdown",
            category=EventCategory.SYSTEM
        )

# Singleton instance
_instance = None

def get_notification_manager(config: Dict[str, Any] = None) -> NotificationManager:
    """
    Get the global notification manager instance.
    
    Args:
        config: Configuration options
        
    Returns:
        NotificationManager instance
    """
    global _instance
    
    if _instance is None:
        _instance = NotificationManager(config)
    
    return _instance

# Register UI callback
def register_ui_callback(user_id: str, callback: Callable[[Dict[str, Any]], None]) -> None:
    """
    Register a UI callback for notifications.
    
    Args:
        user_id: User ID or "default" for global callback
        callback: Function to call with notification data
    """
    manager = get_notification_manager()
    ui_handler = manager.router.get_handler(NotificationChannel.UI)
    
    if isinstance(ui_handler, UIChannelHandler):
        ui_handler.register_callback(user_id, callback)

# Helper functions for sending notifications
def send_notification(
    template_id: str,
    data: Dict[str, Any],
    recipient_id: Optional[str] = None,
    priority: Optional[NotificationPriority] = None,
    channels: Optional[List[NotificationChannel]] = None
) -> Optional[str]:
    """
    Send a notification.
    
    Args:
        template_id: Template ID
        data: Template data
        recipient_id: Recipient user ID
        priority: Override default priority
        channels: Override default channels
        
    Returns:
        Notification ID or None if sending failed
    """
    manager = get_notification_manager()
    return manager.send_notification(
        template_id=template_id,
        data=data,
        recipient_id=recipient_id,
        priority=priority,
        channels=channels
    )

def send_system_notification(
    message: str,
    recipient_id: Optional[str] = None,
    priority: NotificationPriority = NotificationPriority.MEDIUM
) -> Optional[str]:
    """
    Send a system notification.
    
    Args:
        message: Notification message
        recipient_id: Recipient user ID
        priority: Notification priority
        
    Returns:
        Notification ID or None if sending failed
    """
    return send_notification(
        template_id="system_notification",
        data={"message": message},
        recipient_id=recipient_id,
        priority=priority
    )

def send_security_alert(
    message: str,
    recipient_id: Optional[str] = None,
    priority: NotificationPriority = NotificationPriority.HIGH
) -> Optional[str]:
    """
    Send a security alert.
    
    Args:
        message: Alert message
        recipient_id: Recipient user ID
        priority: Notification priority
        
    Returns:
        Notification ID or None if sending failed
    """
    return send_notification(
        template_id="security_alert",
        data={"message": message},
        recipient_id=recipient_id,
        priority=priority
    )

def send_detection_result(
    result: str,
    recipient_id: Optional[str] = None,
    priority: NotificationPriority = NotificationPriority.MEDIUM
) -> Optional[str]:
    """
    Send a detection result notification.
    
    Args:
        result: Detection result
        recipient_id: Recipient user ID
        priority: Notification priority
        
    Returns:
        Notification ID or None if sending failed
    """
    return send_notification(
        template_id="detection_result",
        data={"result": result},
        recipient_id=recipient_id,
        priority=priority
    )

def send_process_notification(
    process_name: str,
    success: bool,
    error: Optional[str] = None,
    recipient_id: Optional[str] = None
) -> Optional[str]:
    """
    Send a process notification.
    
    Args:
        process_name: Process name
        success: Whether the process was successful
        error: Error message if failed
        recipient_id: Recipient user ID
        
    Returns:
        Notification ID or None if sending failed
    """
    if success:
        return send_notification(
            template_id="process_complete",
            data={"process_name": process_name},
            recipient_id=recipient_id
        )
    else:
        return send_notification(
            template_id="process_failed",
            data={"process_name": process_name, "error": error or "Unknown error"},
            recipient_id=recipient_id,
            priority=NotificationPriority.HIGH
        )

class NotificationMonitor:
    """Utility class for monitoring notification metrics and performance."""
    
    def __init__(self, notification_manager: NotificationManager):
        """
        Initialize the notification monitor.
        
        Args:
            notification_manager: Notification manager to monitor
        """
        self.notification_manager = notification_manager
        self.telemetry = get_telemetry()
        
        # Schedule periodic metrics collection
        self.metrics_thread = threading.Thread(
            target=self._collect_metrics_periodically,
            daemon=True
        )
        self.metrics_thread.start()
    
    def _collect_metrics_periodically(self) -> None:
        """Periodically collect notification metrics."""
        while True:
            try:
                # Collect metrics
                metrics = self.collect_metrics()
                
                # Record metrics in telemetry
                self.telemetry.debug(
                    "Notification system metrics collected",
                    category=EventCategory.SYSTEM,
                    context={"metrics": metrics}
                )
                
                # Wait for next collection
                time.sleep(60.0)  # Collect every minute
            
            except Exception as e:
                self.telemetry.error(
                    f"Error collecting notification metrics: {e}",
                    category=EventCategory.SYSTEM,
                    exc_info=True
                )
                time.sleep(60.0)
    
    def collect_metrics(self) -> Dict[str, Any]:
        """
        Collect notification metrics.
        
        Returns:
            Dictionary of metrics
        """
        with self.notification_manager.lock:
            # Count notifications by state
            states = {state: 0 for state in NotificationState}
            for notification in self.notification_manager.notifications.values():
                states[notification.state] += 1
            
            # Count notifications by priority
            priorities = {priority: 0 for priority in NotificationPriority}
            for notification in self.notification_manager.notifications.values():
                priorities[notification.priority] += 1
            
            # Count notifications by category
            categories = {category: 0 for category in NotificationCategory}
            for notification in self.notification_manager.notifications.values():
                categories[notification.category] += 1
            
            # Calculate delivery metrics
            total_notifications = len(self.notification_manager.notifications)
            delivered_count = states[NotificationState.DELIVERED]
            failed_count = states[NotificationState.FAILED]
            
            delivery_rate = 0.0
            if total_notifications > 0:
                delivery_rate = delivered_count / total_notifications
            
            # Calculate average delivery time
            delivery_times = []
            for notification in self.notification_manager.notifications.values():
                if notification.delivered_at and notification.created_at:
                    delivery_time = (notification.delivered_at - notification.created_at).total_seconds()
                    delivery_times.append(delivery_time)
            
            avg_delivery_time = 0.0
            if delivery_times:
                avg_delivery_time = sum(delivery_times) / len(delivery_times)
            
            # Count active users
            active_users = len(self.notification_manager.user_notifications)
            
            return {
                "total_notifications": total_notifications,
                "states": {state.value: count for state, count in states.items()},
                "priorities": {priority.value: count for priority, count in priorities.items()},
                "categories": {category.value: count for category, count in categories.items()},
                "delivery_rate": delivery_rate,
                "avg_delivery_time": avg_delivery_time,
                "active_users": active_users,
                "queue_size": self.notification_manager.delivery_queue.qsize()
            }
    
    def get_notification_stats(self, user_id: Optional[str] = None) -> Dict[str, Any]:
        """
        Get notification statistics.
        
        Args:
            user_id: Optional user ID to filter by
            
        Returns:
            Dictionary of notification statistics
        """
        with self.notification_manager.lock:
            if user_id:
                # User-specific stats
                if user_id not in self.notification_manager.user_notifications:
                    return {
                        "total": 0,
                        "unread": 0,
                        "states": {state.value: 0 for state in NotificationState},
                        "categories": {category.value: 0 for category in NotificationCategory}
                    }
                
                # Get notification IDs for the user
                notification_ids = self.notification_manager.user_notifications[user_id]
                
                # Count states and categories
                states = {state: 0 for state in NotificationState}
                categories = {category: 0 for category in NotificationCategory}
                unread = 0
                
                for nid in notification_ids:
                    if nid in self.notification_manager.notifications:
                        notification = self.notification_manager.notifications[nid]
                        states[notification.state] += 1
                        categories[notification.category] += 1
                        
                        if notification.state != NotificationState.READ:
                            unread += 1
                
                return {
                    "total": len(notification_ids),
                    "unread": unread,
                    "states": {state.value: count for state, count in states.items()},
                    "categories": {category.value: count for category, count in categories.items()}
                }
            else:
                # System-wide stats
                states = {state: 0 for state in NotificationState}
                categories = {category: 0 for category in NotificationCategory}
                unread = 0
                
                for notification in self.notification_manager.notifications.values():
                    states[notification.state] += 1
                    categories[notification.category] += 1
                    
                    if notification.state != NotificationState.READ:
                        unread += 1
                
                return {
                    "total": len(self.notification_manager.notifications),
                    "unread": unread,
                    "states": {state.value: count for state, count in states.items()},
                    "categories": {category.value: count for category, count in categories.items()},
                    "active_users": len(self.notification_manager.user_notifications)
                }

def initialize_notification_monitor() -> NotificationMonitor:
    """
    Initialize the notification monitor.
    
    Returns:
        NotificationMonitor instance
    """
    manager = get_notification_manager()
    return NotificationMonitor(manager)