razeri-plugin-api 0.1.1

Extension traits and registries for Razeri plugins
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
// Copyright (C) 2026 Gabriel Shea
// Licensed under either of the Apache License, Version 2.0 or the MIT
// license, at your option.

#![allow(clippy::doc_markdown)]

//! Structured event sink trait and fan-out registry.
//!
//! [`EventSink`] is the extension point for custom observability
//! backends (Kafka, Datadog, Prometheus, etc.).
//! [`EventRegistry`] dispatches events to all registered sinks,
//! with error resilience (one failing sink does not halt dispatch).

use crate::error::EventSinkError;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, RwLock};
use thiserror::Error;

// ── Event types ────────────────────────────────────────────────────────

/// Stable monitoring event envelope emitted by Razeri operations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct RazeriEvent {
    event_id: String,
    timestamp: DateTime<Utc>,
    category: EventCategory,
    severity: EventSeverity,
    workflow: Option<WorkflowContext>,
    subject: EventSubject,
    payload: EventPayload,
}

/// High-level event category used for filtering and aggregation.
#[derive(Debug, Clone, Copy, Hash, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EventCategory {
    /// Data profiling events.
    Profiling,
    /// SQL materialization events.
    Materialization,
    /// Design loading and validation events.
    Design,
    /// Plugin loading and registration events.
    Plugin,
    /// Storage I/O events.
    Storage,
    /// AI and LLM request events.
    Ai,
}

/// Operator-facing severity level for a monitoring event.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EventSeverity {
    /// Informational event — no operator action required.
    Info,
    /// Something unexpected occurred but processing continued.
    Warning,
    /// An operation failed; operator attention is needed.
    Error,
    /// A severe failure requiring immediate attention.
    Critical,
}

/// Correlation context for workflow-scoped operations.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct WorkflowContext {
    /// Stable workflow identifier shared across related events.
    pub workflow_id: String,
    /// Optional request identifier from an API or RPC boundary.
    pub request_id: Option<String>,
    /// Optional actor name such as a user, service account, or agent.
    pub actor: Option<String>,
    /// Optional originating surface such as `cli`, `api`, `web`, or `mcp`.
    pub surface: Option<String>,
}

impl WorkflowContext {
    /// Create a workflow context with the required workflow identifier.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn new(workflow_id: impl Into<String>) -> Result<Self, EventValidationError> {
        let workflow_id = workflow_id.into();
        if workflow_id.trim().is_empty() {
            return Err(EventValidationError::WorkflowIdRequired);
        }

        Ok(Self { workflow_id, request_id: None, actor: None, surface: None })
    }

    /// Attach a request identifier.
    #[must_use]
    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
        self.request_id = Some(request_id.into());
        self
    }

    /// Attach an actor label.
    #[must_use]
    pub fn with_actor(mut self, actor: impl Into<String>) -> Self {
        self.actor = Some(actor.into());
        self
    }

    /// Attach an originating surface label.
    #[must_use]
    pub fn with_surface(mut self, surface: impl Into<String>) -> Self {
        self.surface = Some(surface.into());
        self
    }
}

/// Primary subject for filtering and grouping events.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct EventSubject {
    /// Discriminator classifying the type of subject.
    pub kind: EventSubjectKind,
    /// Subject name (source name, entity name, plugin name, etc.).
    pub name: String,
}

impl EventSubject {
    /// Create a new event subject.
    pub fn new(kind: EventSubjectKind, name: impl Into<String>) -> Self {
        Self { kind, name: name.into() }
    }

    /// Subject representing a source dataset or file.
    pub fn source(name: impl Into<String>) -> Self {
        Self::new(EventSubjectKind::Source, name)
    }

    /// Subject representing an entity.
    pub fn entity(name: impl Into<String>) -> Self {
        Self::new(EventSubjectKind::Entity, name)
    }

    /// Subject representing a design.
    pub fn design(name: impl Into<String>) -> Self {
        Self::new(EventSubjectKind::Design, name)
    }

    /// Subject representing a plugin.
    pub fn plugin(name: impl Into<String>) -> Self {
        Self::new(EventSubjectKind::Plugin, name)
    }

    /// Subject representing a storage path or backend object.
    pub fn storage(name: impl Into<String>) -> Self {
        Self::new(EventSubjectKind::StoragePath, name)
    }

    /// Subject representing an LLM request target.
    pub fn llm_model(name: impl Into<String>) -> Self {
        Self::new(EventSubjectKind::LlmModel, name)
    }
}

/// Subject kind used for filtering and aggregation.
#[derive(Debug, Clone, Copy, Hash, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EventSubjectKind {
    /// A raw data source.
    Source,
    /// A design entity.
    Entity,
    /// A design document.
    Design,
    /// A plugin.
    Plugin,
    /// A storage path or backend object.
    StoragePath,
    /// An LLM model target.
    LlmModel,
}

/// Structured payload variants carried by the event envelope.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum EventPayload {
    /// Data profiling started on a source.
    ProfilingStarted {
        /// Name of the data source being profiled.
        source: String,
    },
    /// Data profiling completed.
    ProfilingCompleted {
        /// Name of the data source that was profiled.
        source: String,
        /// Number of fields discovered.
        fields: usize,
        /// Number of rows sampled.
        rows: usize,
        /// Duration of the profiling run in milliseconds.
        duration_ms: u64,
    },
    /// SQL materialization started for an entity.
    MaterializationStarted {
        /// Name of the entity being materialized.
        entity: String,
        /// Target SQL platform name.
        platform: String,
    },
    /// SQL materialization completed.
    MaterializationCompleted {
        /// Name of the entity that was materialized.
        entity: String,
        /// Target SQL platform name.
        platform: String,
        /// Number of SQL artifacts produced.
        artifacts: usize,
        /// Duration of the materialization run in milliseconds.
        duration_ms: u64,
    },
    /// SQL materialization failed.
    MaterializationFailed {
        /// Name of the design that failed.
        design: String,
        /// Target SQL platform name.
        platform: String,
        /// Human-readable failure description.
        message: String,
    },
    /// Design validated with warning and error counts.
    DesignValidated {
        /// Name of the validated design.
        design: String,
        /// Number of validation errors.
        errors: usize,
        /// Number of validation warnings.
        warnings: usize,
    },
    /// Design document loaded.
    DesignLoaded {
        /// File path or URI from which the design was loaded.
        path: String,
        /// Number of entities in the design.
        entities: usize,
    },
    /// A plugin was loaded.
    PluginLoaded {
        /// Plugin name.
        name: String,
        /// Plugin extension point type (e.g. `"dialect"`).
        plugin_type: String,
        /// Source description (e.g. `"static"` or a library path).
        source: String,
    },
    /// Storage I/O operation completed.
    StorageOperationCompleted {
        /// Operation name (e.g. `"put"`, `"get"`, `"delete"`).
        operation: String,
        /// Storage path of the object.
        path: String,
        /// Number of bytes transferred.
        bytes: u64,
        /// Duration of the operation in milliseconds.
        duration_ms: u64,
    },
    /// Materializer detected a storage feature that the target platform cannot honor.
    /// Emitted instead of panicking (TP-010).
    StorageWarning {
        /// Name of the entity that triggered the warning.
        entity: String,
        /// Storage feature that is unsupported.
        feature: String,
        /// Target SQL platform name.
        platform: String,
        /// Suggested alternative or workaround.
        recommendation: String,
    },
    /// LLM request completed.
    LlmRequestCompleted {
        /// LLM provider name.
        provider: String,
        /// Model identifier used for the request.
        model: String,
        /// Total tokens consumed.
        tokens: u64,
        /// Duration of the request in milliseconds.
        duration_ms: u64,
    },
}

impl EventPayload {
    /// Category derived from the payload variant.
    #[must_use]
    pub fn category(&self) -> EventCategory {
        match self {
            Self::ProfilingStarted { .. } | Self::ProfilingCompleted { .. } => {
                EventCategory::Profiling
            }
            Self::MaterializationStarted { .. } | Self::MaterializationCompleted { .. } => {
                EventCategory::Materialization
            }
            Self::MaterializationFailed { .. } => EventCategory::Materialization,
            Self::DesignValidated { .. } | Self::DesignLoaded { .. } => EventCategory::Design,
            Self::PluginLoaded { .. } => EventCategory::Plugin,
            Self::StorageOperationCompleted { .. } | Self::StorageWarning { .. } => {
                EventCategory::Storage
            }
            Self::LlmRequestCompleted { .. } => EventCategory::Ai,
        }
    }

    /// Severity derived from the payload variant.
    #[must_use]
    pub fn severity(&self) -> EventSeverity {
        match self {
            Self::MaterializationFailed { .. } => EventSeverity::Error,
            Self::DesignValidated { errors, .. } if *errors > 0 => EventSeverity::Error,
            Self::DesignValidated { warnings, .. } if *warnings > 0 => EventSeverity::Warning,
            Self::StorageWarning { .. } => EventSeverity::Warning,
            _ => EventSeverity::Info,
        }
    }

    /// Whether this payload must be correlated to a workflow.
    #[must_use]
    pub fn requires_workflow_context(&self) -> bool {
        match self {
            Self::ProfilingStarted { .. }
            | Self::ProfilingCompleted { .. }
            | Self::MaterializationStarted { .. }
            | Self::MaterializationCompleted { .. }
            | Self::MaterializationFailed { .. }
            | Self::DesignValidated { .. }
            | Self::StorageOperationCompleted { .. }
            | Self::LlmRequestCompleted { .. } => true,
            Self::DesignLoaded { .. } | Self::PluginLoaded { .. } | Self::StorageWarning { .. } => {
                false
            }
        }
    }

    pub(crate) fn name(&self) -> &'static str {
        match self {
            Self::ProfilingStarted { .. } => "profiling_started",
            Self::ProfilingCompleted { .. } => "profiling_completed",
            Self::MaterializationStarted { .. } => "materialization_started",
            Self::MaterializationCompleted { .. } => "materialization_completed",
            Self::MaterializationFailed { .. } => "materialization_failed",
            Self::DesignValidated { .. } => "design_validated",
            Self::DesignLoaded { .. } => "design_loaded",
            Self::PluginLoaded { .. } => "plugin_loaded",
            Self::StorageOperationCompleted { .. } => "storage_operation_completed",
            Self::StorageWarning { .. } => "storage_warning",
            Self::LlmRequestCompleted { .. } => "llm_request_completed",
        }
    }

    fn summary(&self) -> EventSummary {
        match self {
            Self::ProfilingStarted { source } => profiling_started_summary(source),
            Self::ProfilingCompleted { source, fields, rows, duration_ms } => {
                profiling_completed_summary(source, *fields, *rows, *duration_ms)
            }
            Self::MaterializationStarted { entity, platform } => {
                materialization_started_summary(entity, platform)
            }
            Self::MaterializationCompleted { entity, platform, artifacts, duration_ms } => {
                materialization_completed_summary(entity, platform, *artifacts, *duration_ms)
            }
            Self::MaterializationFailed { design, platform, message } => {
                materialization_failed_summary(design, platform, message)
            }
            Self::DesignValidated { design, errors, warnings } => {
                design_validated_summary(design, *errors, *warnings)
            }
            Self::DesignLoaded { path, entities } => design_loaded_summary(path, *entities),
            Self::PluginLoaded { name, plugin_type, source } => {
                plugin_loaded_summary(name, plugin_type, source)
            }
            Self::StorageOperationCompleted { operation, path, bytes, duration_ms } => {
                storage_operation_completed_summary(operation, path, *bytes, *duration_ms)
            }
            Self::StorageWarning { entity, feature, platform, recommendation } => {
                storage_warning_summary(entity, feature, platform, recommendation)
            }
            Self::LlmRequestCompleted { provider, model, tokens, duration_ms } => {
                llm_request_completed_summary(provider, model, *tokens, *duration_ms)
            }
        }
    }
}

/// Build summary text for a profiling-started payload.
/// Parameters:
/// - source: Source name being profiled.
fn profiling_started_summary(source: &str) -> EventSummary {
    EventSummary {
        title: "Profiling started".to_string(),
        detail: format!("Profiling started for source '{source}'"),
    }
}

/// Build summary text for a profiling-completed payload.
/// Parameters:
/// - source: Source name that was profiled.
/// - fields: Number of discovered fields.
/// - rows: Number of sampled rows.
/// - duration_ms: Profiling runtime in milliseconds.
fn profiling_completed_summary(
    source: &str,
    fields: usize,
    rows: usize,
    duration_ms: u64,
) -> EventSummary {
    EventSummary {
        title: "Profiling completed".to_string(),
        detail: format!(
            "Source '{source}' profiled with {fields} fields, {rows} rows in {duration_ms} ms"
        ),
    }
}

/// Build summary text for a materialization-started payload.
/// Parameters:
/// - entity: Entity being materialized.
/// - platform: Target SQL platform.
fn materialization_started_summary(entity: &str, platform: &str) -> EventSummary {
    EventSummary {
        title: "Materialization started".to_string(),
        detail: format!("Entity '{entity}' started materialization for {platform}"),
    }
}

/// Build summary text for a materialization-completed payload.
/// Parameters:
/// - entity: Entity that finished materialization.
/// - platform: Target SQL platform.
/// - artifacts: Number of generated artifacts.
/// - duration_ms: Materialization runtime in milliseconds.
fn materialization_completed_summary(
    entity: &str,
    platform: &str,
    artifacts: usize,
    duration_ms: u64,
) -> EventSummary {
    EventSummary {
        title: "Materialization completed".to_string(),
        detail: format!(
            "Entity '{entity}' produced {artifacts} artifacts for {platform} in {duration_ms} ms"
        ),
    }
}

/// Build summary text for a materialization-failed payload.
/// Parameters:
/// - design: Design that failed.
/// - platform: Target SQL platform.
/// - message: Failure reason.
fn materialization_failed_summary(design: &str, platform: &str, message: &str) -> EventSummary {
    EventSummary {
        title: "Materialization failed".to_string(),
        detail: format!("Design '{design}' failed materialization for {platform}: {message}"),
    }
}

/// Build summary text for a design-validated payload.
/// Parameters:
/// - design: Design name.
/// - errors: Validation error count.
/// - warnings: Validation warning count.
fn design_validated_summary(design: &str, errors: usize, warnings: usize) -> EventSummary {
    EventSummary {
        title: "Design validated".to_string(),
        detail: format!("Design '{design}' validated with {errors} errors and {warnings} warnings"),
    }
}

/// Build summary text for a design-loaded payload.
/// Parameters:
/// - path: Loaded path or URI.
/// - entities: Number of entities in the loaded design.
fn design_loaded_summary(path: &str, entities: usize) -> EventSummary {
    EventSummary {
        title: "Design loaded".to_string(),
        detail: format!("Loaded design from '{path}' with {entities} entities"),
    }
}

/// Build summary text for a plugin-loaded payload.
/// Parameters:
/// - name: Plugin name.
/// - plugin_type: Plugin extension-point type.
/// - source: Plugin load source descriptor.
fn plugin_loaded_summary(name: &str, plugin_type: &str, source: &str) -> EventSummary {
    EventSummary {
        title: "Plugin loaded".to_string(),
        detail: format!("Loaded {plugin_type} plugin '{name}' from {source}"),
    }
}

/// Build summary text for a storage-operation-completed payload.
/// Parameters:
/// - operation: Storage operation name.
/// - path: Object path processed by the operation.
/// - bytes: Number of processed bytes.
/// - duration_ms: Operation runtime in milliseconds.
fn storage_operation_completed_summary(
    operation: &str,
    path: &str,
    bytes: u64,
    duration_ms: u64,
) -> EventSummary {
    EventSummary {
        title: "Storage operation completed".to_string(),
        detail: format!(
            "Operation '{operation}' processed {bytes} bytes at '{path}' in {duration_ms} ms"
        ),
    }
}

/// Build summary text for a storage-warning payload.
/// Parameters:
/// - entity: Entity associated with the warning.
/// - feature: Unsupported storage feature.
/// - platform: Target SQL platform.
/// - recommendation: Suggested workaround.
fn storage_warning_summary(
    entity: &str,
    feature: &str,
    platform: &str,
    recommendation: &str,
) -> EventSummary {
    EventSummary {
        title: "Storage warning".to_string(),
        detail: format!(
            "Entity '{entity}': feature '{feature}' unavailable on '{platform}'; {recommendation}"
        ),
    }
}

/// Build summary text for an LLM-request-completed payload.
/// Parameters:
/// - provider: LLM provider name.
/// - model: Model identifier.
/// - tokens: Total consumed tokens.
/// - duration_ms: Request runtime in milliseconds.
fn llm_request_completed_summary(
    provider: &str,
    model: &str,
    tokens: u64,
    duration_ms: u64,
) -> EventSummary {
    EventSummary {
        title: "LLM request completed".to_string(),
        detail: format!(
            "Provider '{provider}' model '{model}' used {tokens} tokens in {duration_ms} ms"
        ),
    }
}

/// Filter keys that can be derived from a canonical event alone.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct EventFilterKeys {
    /// Event category derived from the payload.
    pub category: EventCategory,
    /// Event severity derived from the payload.
    pub severity: EventSeverity,
    /// Workflow identifier if the event was workflow-scoped.
    pub workflow_id: Option<String>,
    /// Kind of the primary event subject.
    pub subject_kind: EventSubjectKind,
    /// Name of the primary event subject.
    pub subject_name: String,
    /// Actor label from the workflow context.
    pub actor: Option<String>,
    /// Originating surface label from the workflow context.
    pub surface: Option<String>,
}

/// Human-readable summary derived from a canonical event.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct EventSummary {
    /// Short summary title.
    pub title: String,
    /// Longer human-readable detail string.
    pub detail: String,
}

/// Validation error for canonical monitoring events.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum EventValidationError {
    /// A workflow-scoped payload was submitted without a workflow context.
    #[error("workflow-scoped event payload '{payload}' requires workflow context")]
    WorkflowContextRequired {
        /// Name of the payload type that requires workflow context.
        payload: String,
    },
    /// The workflow context was supplied with an empty `workflow_id`.
    #[error("workflow context requires a non-empty workflow_id")]
    WorkflowIdRequired,
}

impl RazeriEvent {
    /// Create a new non-workflow-scoped event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn new(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        subject: EventSubject,
        payload: EventPayload,
    ) -> Result<Self, EventValidationError> {
        Self::build(event_id.into(), timestamp, None, subject, payload)
    }

    /// Create a new workflow-scoped event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn new_with_workflow(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        workflow: WorkflowContext,
        subject: EventSubject,
        payload: EventPayload,
    ) -> Result<Self, EventValidationError> {
        Self::build(event_id.into(), timestamp, Some(workflow), subject, payload)
    }

    fn build(
        event_id: String,
        timestamp: DateTime<Utc>,
        workflow: Option<WorkflowContext>,
        subject: EventSubject,
        payload: EventPayload,
    ) -> Result<Self, EventValidationError> {
        let event = Self {
            event_id,
            timestamp,
            category: payload.category(),
            severity: payload.severity(),
            workflow,
            subject,
            payload,
        };

        event.validate()?;
        Ok(event)
    }

    /// Validate that the canonical envelope is internally consistent.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn validate(&self) -> Result<(), EventValidationError> {
        if self.payload.requires_workflow_context() && self.workflow.is_none() {
            return Err(EventValidationError::WorkflowContextRequired {
                payload: self.payload.name().to_string(),
            });
        }

        if self.workflow.as_ref().is_some_and(|workflow| workflow.workflow_id.trim().is_empty()) {
            return Err(EventValidationError::WorkflowIdRequired);
        }

        Ok(())
    }

    /// Stable event identifier.
    #[must_use]
    pub fn event_id(&self) -> &str {
        &self.event_id
    }

    /// Event timestamp.
    #[must_use]
    pub fn timestamp(&self) -> DateTime<Utc> {
        self.timestamp
    }

    /// Derived event category.
    #[must_use]
    pub fn category(&self) -> EventCategory {
        self.category
    }

    /// Derived event severity.
    #[must_use]
    pub fn severity(&self) -> EventSeverity {
        self.severity
    }

    /// Optional workflow correlation context.
    #[must_use]
    pub fn workflow(&self) -> Option<&WorkflowContext> {
        self.workflow.as_ref()
    }

    /// Primary event subject.
    #[must_use]
    pub fn subject(&self) -> &EventSubject {
        &self.subject
    }

    /// Structured event payload.
    #[must_use]
    pub fn payload(&self) -> &EventPayload {
        &self.payload
    }

    /// Derived filter keys suitable for summaries and operator UIs.
    #[must_use]
    pub fn filter_keys(&self) -> EventFilterKeys {
        EventFilterKeys {
            category: self.category,
            severity: self.severity,
            workflow_id: self.workflow.as_ref().map(|workflow| workflow.workflow_id.clone()),
            subject_kind: self.subject.kind,
            subject_name: self.subject.name.clone(),
            actor: self.workflow.as_ref().and_then(|workflow| workflow.actor.clone()),
            surface: self.workflow.as_ref().and_then(|workflow| workflow.surface.clone()),
        }
    }

    /// Human-readable summary derived from the canonical event.
    #[must_use]
    pub fn summary(&self) -> EventSummary {
        self.payload.summary()
    }

    /// Convenience constructor for a design validation event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn design_validated(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        workflow: WorkflowContext,
        design: impl Into<String>,
        errors: usize,
        warnings: usize,
    ) -> Result<Self, EventValidationError> {
        let design = design.into();
        Self::new_with_workflow(
            event_id,
            timestamp,
            workflow,
            EventSubject::design(design.clone()),
            EventPayload::DesignValidated { design, errors, warnings },
        )
    }

    /// Convenience constructor for a materialization-started event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn materialization_started(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        workflow: WorkflowContext,
        entity: impl Into<String>,
        platform: impl Into<String>,
    ) -> Result<Self, EventValidationError> {
        let entity = entity.into();
        let platform = platform.into();
        Self::new_with_workflow(
            event_id,
            timestamp,
            workflow,
            EventSubject::entity(entity.clone()),
            EventPayload::MaterializationStarted { entity, platform },
        )
    }

    /// Convenience constructor for a materialization-completed event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn materialization_completed(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        workflow: WorkflowContext,
        entity: impl Into<String>,
        platform: impl Into<String>,
        artifacts: usize,
        duration_ms: u64,
    ) -> Result<Self, EventValidationError> {
        let entity = entity.into();
        let platform = platform.into();
        Self::new_with_workflow(
            event_id,
            timestamp,
            workflow,
            EventSubject::entity(entity.clone()),
            EventPayload::MaterializationCompleted { entity, platform, artifacts, duration_ms },
        )
    }

    /// Convenience constructor for a materialization-failed event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn materialization_failed(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        workflow: WorkflowContext,
        design: impl Into<String>,
        platform: impl Into<String>,
        message: impl Into<String>,
    ) -> Result<Self, EventValidationError> {
        let design = design.into();
        let platform = platform.into();
        let message = message.into();
        Self::new_with_workflow(
            event_id,
            timestamp,
            workflow,
            EventSubject::design(design.clone()),
            EventPayload::MaterializationFailed { design, platform, message },
        )
    }

    /// Convenience constructor for a profiling-started event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn profiling_started(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        workflow: WorkflowContext,
        source: impl Into<String>,
    ) -> Result<Self, EventValidationError> {
        let source = source.into();
        Self::new_with_workflow(
            event_id,
            timestamp,
            workflow,
            EventSubject::source(source.clone()),
            EventPayload::ProfilingStarted { source },
        )
    }

    /// Convenience constructor for a profiling-completed event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn profiling_completed(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        workflow: WorkflowContext,
        source: impl Into<String>,
        fields: usize,
        rows: usize,
        duration_ms: u64,
    ) -> Result<Self, EventValidationError> {
        let source = source.into();
        Self::new_with_workflow(
            event_id,
            timestamp,
            workflow,
            EventSubject::source(source.clone()),
            EventPayload::ProfilingCompleted { source, fields, rows, duration_ms },
        )
    }

    /// Convenience constructor for a design-loaded event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn design_loaded(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        path: impl Into<String>,
        entities: usize,
    ) -> Result<Self, EventValidationError> {
        let path = path.into();
        Self::new(
            event_id,
            timestamp,
            EventSubject::design(path.clone()),
            EventPayload::DesignLoaded { path, entities },
        )
    }

    /// Convenience constructor for a plugin-loaded event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn plugin_loaded(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        name: impl Into<String>,
        plugin_type: impl Into<String>,
        source: impl Into<String>,
    ) -> Result<Self, EventValidationError> {
        let name = name.into();
        let plugin_type = plugin_type.into();
        let source = source.into();
        Self::new(
            event_id,
            timestamp,
            EventSubject::plugin(name.clone()),
            EventPayload::PluginLoaded { name, plugin_type, source },
        )
    }

    /// Convenience constructor for a storage-operation-completed event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn storage_operation_completed(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        workflow: WorkflowContext,
        operation: impl Into<String>,
        path: impl Into<String>,
        bytes: u64,
        duration_ms: u64,
    ) -> Result<Self, EventValidationError> {
        let operation = operation.into();
        let path = path.into();
        Self::new_with_workflow(
            event_id,
            timestamp,
            workflow,
            EventSubject::storage(path.clone()),
            EventPayload::StorageOperationCompleted { operation, path, bytes, duration_ms },
        )
    }

    /// Convenience constructor for an LLM-request-completed event.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    pub fn llm_request_completed(
        event_id: impl Into<String>,
        timestamp: DateTime<Utc>,
        workflow: WorkflowContext,
        provider: impl Into<String>,
        model: impl Into<String>,
        tokens: u64,
        duration_ms: u64,
    ) -> Result<Self, EventValidationError> {
        let provider = provider.into();
        let model = model.into();
        Self::new_with_workflow(
            event_id,
            timestamp,
            workflow,
            EventSubject::llm_model(model.clone()),
            EventPayload::LlmRequestCompleted { provider, model, tokens, duration_ms },
        )
    }
}

/// Shared interface for components that emit canonical monitoring events.
#[async_trait]
pub trait EventEmitter: Send + Sync {
    /// Emit a canonical event into the monitoring pipeline.
    async fn emit_event(&self, event: RazeriEvent) -> Vec<(String, EventSinkError)>;
}

// ── EventSink trait ────────────────────────────────────────────────────

/// Sink that receives structured events from Razeri operations.
///
/// Implementations should be non-blocking and resilient to transient
/// failures (e.g., network issues). Razeri will continue operating
/// even if an event sink fails.
#[async_trait]
pub trait EventSink: Send + Sync {
    /// Machine-readable sink name.
    fn name(&self) -> &str;

    /// Handle an event. Should not block or panic.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    async fn on_event(&self, event: &RazeriEvent) -> Result<(), EventSinkError>;

    /// Flush any buffered events.
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails.
    async fn flush(&self) -> Result<(), EventSinkError>;
}

// ── EventRegistry ──────────────────────────────────────────────────────

/// Registry that dispatches events to all registered sinks.
///
/// Errors from individual sinks are logged but do **not** halt the
/// pipeline — this is the "fire and continue" pattern.
pub struct EventRegistry {
    sinks: Vec<Arc<dyn EventSink>>,
    history: RwLock<Vec<RazeriEvent>>,
}

impl EventRegistry {
    /// Create an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self { sinks: Vec::new(), history: RwLock::new(Vec::new()) }
    }

    /// Register an event sink.
    pub fn register(&mut self, sink: Arc<dyn EventSink>) {
        self.sinks.push(sink);
    }

    /// Dispatch an event to all sinks.
    ///
    /// Errors from individual sinks are collected but do not propagate —
    /// all sinks are attempted regardless of failures.
    pub async fn emit(&self, event: &RazeriEvent) -> Vec<(String, EventSinkError)> {
        self.record(event.clone());
        let mut errors = Vec::new();
        for sink in &self.sinks {
            if let Err(e) = sink.on_event(event).await {
                errors.push((sink.name().to_string(), e));
            }
        }
        errors
    }

    /// Record an event without dispatching it to sinks.
    pub fn record(&self, event: RazeriEvent) {
        self.history.write().unwrap_or_else(std::sync::PoisonError::into_inner).push(event);
    }

    /// Return all recorded events in chronological order.
    pub fn events(&self) -> Vec<RazeriEvent> {
        self.history.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
    }

    /// Return the most recent events in chronological order.
    pub fn recent_events(&self, limit: usize) -> Vec<RazeriEvent> {
        let events = self.history.read().unwrap_or_else(std::sync::PoisonError::into_inner);
        let start = events.len().saturating_sub(limit);
        events[start..].to_vec()
    }

    /// Return events associated with the provided workflow identifier.
    pub fn events_for_workflow(&self, workflow_id: &str) -> Vec<RazeriEvent> {
        self.history
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .iter()
            .filter(|event| {
                event.workflow().is_some_and(|workflow| workflow.workflow_id == workflow_id)
            })
            .cloned()
            .collect()
    }

    /// Return human-readable summaries for the most recent events.
    pub fn recent_summaries(&self, limit: usize) -> Vec<EventSummary> {
        self.recent_events(limit).into_iter().map(|event| event.summary()).collect()
    }

    /// Flush all sinks.
    pub async fn flush_all(&self) -> Vec<(String, EventSinkError)> {
        let mut errors = Vec::new();
        for sink in &self.sinks {
            if let Err(e) = sink.flush().await {
                errors.push((sink.name().to_string(), e));
            }
        }
        errors
    }

    /// Number of registered sinks.
    pub fn len(&self) -> usize {
        self.sinks.len()
    }

    /// Whether the registry has no sinks.
    pub fn is_empty(&self) -> bool {
        self.sinks.is_empty()
    }

    /// Execute a flexible query against the recorded event history.
    pub fn query(&self, q: &EventQuery) -> Vec<RazeriEvent> {
        let history = self.history.read().unwrap_or_else(std::sync::PoisonError::into_inner);
        let iter = history.iter().filter(|e| {
            q.category.is_none_or(|c| e.category() == c)
                && q.min_severity.is_none_or(|s| e.severity() >= s)
                && q.workflow_id
                    .as_ref()
                    .is_none_or(|wf| e.workflow().is_some_and(|w| w.workflow_id == *wf))
                && q.subject_name.as_ref().is_none_or(|n| e.subject().name == *n)
                && q.subject_kind.is_none_or(|k| e.subject().kind == k)
                && q.since.is_none_or(|t| e.timestamp() >= t)
        });
        match q.limit {
            Some(n) => iter.take(n).cloned().collect(),
            None => iter.cloned().collect(),
        }
    }
}

/// Flexible event query for filtering and pagination.
///
/// All fields are optional. When `None`, no filtering is applied for that
/// dimension. Combine fields to narrow results (they are `ANDed` together).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EventQuery {
    /// Filter by event category.
    pub category: Option<EventCategory>,
    /// Filter to events at or above this severity.
    pub min_severity: Option<EventSeverity>,
    /// Filter by workflow identifier.
    pub workflow_id: Option<String>,
    /// Filter by subject name.
    pub subject_name: Option<String>,
    /// Filter by subject kind.
    pub subject_kind: Option<EventSubjectKind>,
    /// Only include events at or after this timestamp.
    pub since: Option<DateTime<Utc>>,
    /// Maximum number of events to return.
    pub limit: Option<usize>,
}

impl Default for EventRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl EventEmitter for EventRegistry {
    async fn emit_event(&self, event: RazeriEvent) -> Vec<(String, EventSinkError)> {
        self.emit(&event).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn sample_timestamp() -> DateTime<Utc> {
        DateTime::parse_from_rfc3339("2026-03-13T12:34:56Z")
            .expect("valid timestamp fixture")
            .with_timezone(&Utc)
    }

    fn sample_workflow() -> WorkflowContext {
        WorkflowContext::new("workflow-123")
            .expect("workflow id should be valid")
            .with_request_id("request-456")
            .with_actor("analyst@example.com")
            .with_surface("web")
    }

    struct CountingSink {
        event_count: AtomicUsize,
        flush_count: AtomicUsize,
    }

    impl CountingSink {
        fn new() -> Self {
            Self { event_count: AtomicUsize::new(0), flush_count: AtomicUsize::new(0) }
        }

        fn events_received(&self) -> usize {
            self.event_count.load(Ordering::SeqCst)
        }

        fn flushes(&self) -> usize {
            self.flush_count.load(Ordering::SeqCst)
        }
    }

    #[async_trait]
    impl EventSink for CountingSink {
        fn name(&self) -> &'static str {
            "counting"
        }

        async fn on_event(&self, _event: &RazeriEvent) -> Result<(), EventSinkError> {
            self.event_count.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }

        async fn flush(&self) -> Result<(), EventSinkError> {
            self.flush_count.fetch_add(1, Ordering::SeqCst);
            Ok(())
        }
    }

    struct FailingSink;

    #[async_trait]
    impl EventSink for FailingSink {
        fn name(&self) -> &'static str {
            "failing"
        }

        async fn on_event(&self, _event: &RazeriEvent) -> Result<(), EventSinkError> {
            Err(EventSinkError::SinkError("intentional failure".to_string()))
        }

        async fn flush(&self) -> Result<(), EventSinkError> {
            Err(EventSinkError::SinkError("intentional failure".to_string()))
        }
    }

    fn sample_event() -> RazeriEvent {
        RazeriEvent::new_with_workflow(
            "event-123",
            sample_timestamp(),
            sample_workflow(),
            EventSubject::source("test.csv"),
            EventPayload::ProfilingCompleted {
                source: "test.csv".to_string(),
                fields: 10,
                rows: 1000,
                duration_ms: 42,
            },
        )
        .expect("workflow-scoped sample event should be valid")
    }

    fn plugin_event() -> RazeriEvent {
        RazeriEvent::new(
            "event-plugin-1",
            sample_timestamp(),
            EventSubject::plugin("builtin-logger"),
            EventPayload::PluginLoaded {
                name: "builtin-logger".to_string(),
                plugin_type: "event_sink".to_string(),
                source: "builtin".to_string(),
            },
        )
        .expect("plugin events are not workflow scoped")
    }

    #[tokio::test]
    async fn event_dispatched_to_all_sinks() {
        let sink1 = Arc::new(CountingSink::new());
        let sink2 = Arc::new(CountingSink::new());

        let mut registry = EventRegistry::new();
        registry.register(sink1.clone());
        registry.register(sink2.clone());

        let errors = registry.emit(&sample_event()).await;
        assert!(errors.is_empty());
        assert_eq!(sink1.events_received(), 1);
        assert_eq!(sink2.events_received(), 1);
    }

    #[tokio::test]
    async fn sink_failure_does_not_halt_dispatch() {
        let good_sink = Arc::new(CountingSink::new());
        let bad_sink: Arc<dyn EventSink> = Arc::new(FailingSink);

        let mut registry = EventRegistry::new();
        registry.register(bad_sink);
        registry.register(good_sink.clone());

        let errors = registry.emit(&sample_event()).await;
        // Failing sink produced an error, but good sink still received the event
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].0, "failing");
        assert_eq!(good_sink.events_received(), 1);
    }

    #[tokio::test]
    async fn flush_all_flushes_every_sink() {
        let sink1 = Arc::new(CountingSink::new());
        let sink2 = Arc::new(CountingSink::new());

        let mut registry = EventRegistry::new();
        registry.register(sink1.clone());
        registry.register(sink2.clone());

        let errors = registry.flush_all().await;
        assert!(errors.is_empty());
        assert_eq!(sink1.flushes(), 1);
        assert_eq!(sink2.flushes(), 1);
    }

    #[tokio::test]
    async fn emitted_events_are_recorded_and_queryable() {
        let registry = EventRegistry::new();
        registry.emit_event(sample_event()).await;
        registry.emit_event(plugin_event()).await;

        let recorded = registry.events();
        assert_eq!(recorded.len(), 2);

        let workflow_events = registry.events_for_workflow("workflow-123");
        assert_eq!(workflow_events.len(), 1);
        assert_eq!(workflow_events[0].category(), EventCategory::Profiling);

        let summaries = registry.recent_summaries(2);
        assert_eq!(summaries.len(), 2);
        assert_eq!(summaries[0].title, "Profiling completed");
        assert_eq!(summaries[1].title, "Plugin loaded");
    }

    #[test]
    fn materialization_failure_has_error_severity_and_summary() {
        let event = RazeriEvent::materialization_failed(
            "event-materialization-failed",
            sample_timestamp(),
            sample_workflow(),
            "sales_design",
            "duckdb",
            "dialect mismatch",
        )
        .expect("materialization failure event should be valid");

        assert_eq!(event.category(), EventCategory::Materialization);
        assert_eq!(event.severity(), EventSeverity::Error);
        assert!(event.summary().detail.contains("dialect mismatch"));
    }

    #[test]
    fn event_serializes_to_json() {
        let event = sample_event();
        let json = serde_json::to_string(&event);
        assert!(json.is_ok());
        let json_str = json.unwrap();
        assert!(json_str.contains("profiling_completed"));
        assert!(json_str.contains("test.csv"));
        assert!(json_str.contains("workflow-123"));
    }

    #[test]
    fn workflow_scoped_event_requires_workflow_context() {
        let event = RazeriEvent::new(
            "event-missing-workflow",
            sample_timestamp(),
            EventSubject::source("missing.csv"),
            EventPayload::ProfilingStarted { source: "missing.csv".to_string() },
        );

        assert_eq!(
            event,
            Err(EventValidationError::WorkflowContextRequired {
                payload: "profiling_started".to_string(),
            })
        );
    }

    #[test]
    fn event_round_trips_through_json_without_losing_meaning() {
        let event = sample_event();
        let json = serde_json::to_string(&event).expect("event should serialize");
        let round_trip: RazeriEvent =
            serde_json::from_str(&json).expect("event should deserialize");

        assert_eq!(event, round_trip);
        assert_eq!(round_trip.validate(), Ok(()));
    }

    #[test]
    fn summaries_and_filter_keys_are_derived_from_canonical_event() {
        let event = sample_event();

        let keys = event.filter_keys();
        assert_eq!(keys.category, EventCategory::Profiling);
        assert_eq!(keys.severity, EventSeverity::Info);
        assert_eq!(keys.workflow_id.as_deref(), Some("workflow-123"));
        assert_eq!(keys.subject_kind, EventSubjectKind::Source);
        assert_eq!(keys.subject_name, "test.csv");
        assert_eq!(keys.actor.as_deref(), Some("analyst@example.com"));
        assert_eq!(keys.surface.as_deref(), Some("web"));

        let summary = event.summary();
        assert_eq!(summary.title, "Profiling completed");
        assert!(summary.detail.contains("10 fields"));
        assert!(summary.detail.contains("1000 rows"));
    }

    #[test]
    fn non_workflow_scoped_events_can_be_created_without_workflow_context() {
        let event = plugin_event();

        assert_eq!(event.category(), EventCategory::Plugin);
        assert_eq!(event.severity(), EventSeverity::Info);
        assert!(event.workflow().is_none());
    }

    #[test]
    fn profiling_started_constructs_with_source_subject() {
        let event = RazeriEvent::profiling_started(
            "ps-1",
            sample_timestamp(),
            sample_workflow(),
            "customers.csv",
        )
        .unwrap();
        assert_eq!(event.category(), EventCategory::Profiling);
        assert_eq!(event.subject().kind, EventSubjectKind::Source);
        assert_eq!(event.summary().title, "Profiling started");
    }

    #[test]
    fn profiling_completed_constructs_with_stats() {
        let event = RazeriEvent::profiling_completed(
            "pc-1",
            sample_timestamp(),
            sample_workflow(),
            "customers.csv",
            10,
            5000,
            123,
        )
        .unwrap();
        assert_eq!(event.category(), EventCategory::Profiling);
        assert!(event.summary().detail.contains("10 fields"));
        assert!(event.summary().detail.contains("5000 rows"));
    }

    #[test]
    fn design_loaded_constructs_without_workflow() {
        let event =
            RazeriEvent::design_loaded("dl-1", sample_timestamp(), "designs/retail.yaml", 3)
                .unwrap();
        assert_eq!(event.category(), EventCategory::Design);
        assert!(event.workflow().is_none());
        assert!(event.summary().detail.contains("3 entities"));
    }

    #[test]
    fn plugin_loaded_constructs_without_workflow() {
        let event = RazeriEvent::plugin_loaded(
            "pl-1",
            sample_timestamp(),
            "PostgresDialect",
            "dialect",
            "inventory",
        )
        .unwrap();
        assert_eq!(event.category(), EventCategory::Plugin);
        assert_eq!(event.subject().kind, EventSubjectKind::Plugin);
        assert!(event.summary().detail.contains("dialect"));
    }

    #[test]
    fn storage_operation_completed_constructs_with_workflow() {
        let event = RazeriEvent::storage_operation_completed(
            "so-1",
            sample_timestamp(),
            sample_workflow(),
            "move",
            "/data/file.csv",
            1024,
            50,
        )
        .unwrap();
        assert_eq!(event.category(), EventCategory::Storage);
        assert_eq!(event.subject().kind, EventSubjectKind::StoragePath);
    }

    #[test]
    fn llm_request_completed_constructs_with_workflow() {
        let event = RazeriEvent::llm_request_completed(
            "lr-1",
            sample_timestamp(),
            sample_workflow(),
            "ollama",
            "llama3",
            500,
            3000,
        )
        .unwrap();
        assert_eq!(event.category(), EventCategory::Ai);
        assert_eq!(event.subject().kind, EventSubjectKind::LlmModel);
        assert!(event.summary().detail.contains("500 tokens"));
    }

    #[test]
    fn query_returns_all_events_when_empty() {
        let registry = EventRegistry::new();
        registry.record(sample_event());
        registry.record(plugin_event());

        let results = registry.query(&EventQuery::default());
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn query_filters_by_category() {
        let registry = EventRegistry::new();
        registry.record(sample_event());
        registry.record(plugin_event());

        let results = registry
            .query(&EventQuery { category: Some(EventCategory::Plugin), ..Default::default() });
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].category(), EventCategory::Plugin);
    }

    #[test]
    fn query_filters_by_min_severity() {
        let registry = EventRegistry::new();
        registry.record(sample_event()); // Info
        let error_event = RazeriEvent::materialization_failed(
            "err-1",
            sample_timestamp(),
            sample_workflow(),
            "design-a",
            "PostgreSQL",
            "connection error",
        )
        .unwrap();
        registry.record(error_event);

        let results = registry
            .query(&EventQuery { min_severity: Some(EventSeverity::Error), ..Default::default() });
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].severity(), EventSeverity::Error);
    }

    #[test]
    fn query_filters_by_workflow_id() {
        let registry = EventRegistry::new();
        registry.record(sample_event()); // workflow-123
        registry.record(plugin_event()); // no workflow

        let results = registry.query(&EventQuery {
            workflow_id: Some("workflow-123".to_string()),
            ..Default::default()
        });
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn query_respects_limit() {
        let registry = EventRegistry::new();
        registry.record(sample_event());
        registry.record(plugin_event());

        let results = registry.query(&EventQuery { limit: Some(1), ..Default::default() });
        assert_eq!(results.len(), 1);
    }

    // ── Snapshot tests ──────────────────────────────────────────────────

    #[test]
    fn snapshot_profiling_completed_json_shape() {
        let event = sample_event();
        let val: serde_json::Value = serde_json::to_value(&event).unwrap();
        let obj = val.as_object().unwrap();

        // Envelope fields
        assert!(obj.contains_key("event_id"));
        assert!(obj.contains_key("timestamp"));
        assert!(obj.contains_key("category"));
        assert!(obj.contains_key("severity"));
        assert!(obj.contains_key("workflow"));
        assert!(obj.contains_key("subject"));
        assert!(obj.contains_key("payload"));

        // Payload is internally tagged with "kind"
        let payload = obj["payload"].as_object().unwrap();
        assert_eq!(payload["kind"], "profiling_completed");
        assert!(payload.contains_key("source"));
        assert!(payload.contains_key("fields"));
        assert!(payload.contains_key("rows"));
        assert!(payload.contains_key("duration_ms"));

        // Subject has kind+name
        let subject = obj["subject"].as_object().unwrap();
        assert_eq!(subject["kind"], "source");
        assert!(subject.contains_key("name"));
    }

    #[test]
    fn snapshot_event_round_trip_preserves_identity() {
        let event = sample_event();
        let json = serde_json::to_string(&event).unwrap();
        let roundtrip: RazeriEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(roundtrip.event_id(), event.event_id());
        assert_eq!(roundtrip.category(), event.category());
        assert_eq!(roundtrip.severity(), event.severity());
        assert_eq!(roundtrip.subject().name, event.subject().name);
    }

    #[test]
    fn snapshot_materialization_failed_json_shape() {
        let event = RazeriEvent::materialization_failed(
            "snap-mat-fail",
            sample_timestamp(),
            sample_workflow(),
            "sales_design",
            "duckdb",
            "type mismatch",
        )
        .unwrap();
        let val: serde_json::Value = serde_json::to_value(&event).unwrap();
        let payload = val["payload"].as_object().unwrap();
        assert_eq!(payload["kind"], "materialization_failed");
        assert_eq!(payload["design"], "sales_design");
        assert_eq!(payload["platform"], "duckdb");
        assert_eq!(payload["message"], "type mismatch");
    }

    #[test]
    fn snapshot_plugin_loaded_json_shape() {
        let event = plugin_event();
        let val: serde_json::Value = serde_json::to_value(&event).unwrap();
        let payload = val["payload"].as_object().unwrap();
        assert_eq!(payload["kind"], "plugin_loaded");
        assert!(payload.contains_key("name"));
        assert!(payload.contains_key("plugin_type"));
        assert!(payload.contains_key("source"));
    }

    #[test]
    fn snapshot_event_summary_format_is_stable() {
        let event = sample_event();
        let summary = event.summary();
        assert_eq!(summary.title, "Profiling completed");
        assert!(summary.detail.contains("test.csv"));
        assert!(summary.detail.contains("10"));
        assert!(summary.detail.contains("100"));
    }

    #[test]
    fn snapshot_filter_keys_are_stable() {
        let event = sample_event();
        let keys = event.filter_keys();
        assert_eq!(keys.category, EventCategory::Profiling);
        assert_eq!(keys.severity, EventSeverity::Info);
        assert_eq!(keys.workflow_id.as_deref(), Some("workflow-123"));
        assert_eq!(keys.subject_name, "test.csv");
    }
}