wasm4pm-compat 26.6.5

Minimal paper-complete, feature-capped Rust process-evidence crate. Start with compatibility. Graduate to execution.
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
//! Directly-Follows Graph (DFG) **shape** — the graph, not the discovery
//! algorithm.
//!
//! A DFG records, for a process, which activities directly follow which, and how
//! often. This module models the *graph value*: a [`crate::dfg::Dfg`] is a set of
//! [`crate::dfg::DfgNode`]s (activities) joined by weighted [`crate::dfg::DfgEdge`]s, each carrying a
//! [`crate::dfg::DfgWeight`] (a directly-follows frequency).
//!
//! ## Structure only — no discovery
//!
//! This crate does **not** discover a DFG from a log. Computing directly-follows
//! relations and frequencies *is* a discovery engine and graduates to
//! `wasm4pm`. To make that boundary unmistakable, asking a DFG to behave as if
//! it had been discovered when it is empty is refused as the named law
//! [`crate::dfg::DfgRefusal::DiscoveryRequired`].
//!
//! [`crate::dfg::Dfg::validate`] checks only *graph* shape: edges reference declared nodes,
//! weights are non-negative, and the graph is non-empty.
//!
//! ## Graduation to `wasm4pm`
//!
//! DFG *discovery* (from an [`crate::eventlog::EventLog`] or [`crate::ocel::OcelLog`]),
//! filtering, and DFG-based conformance graduate to `wasm4pm`. This crate only
//! represents and structurally validates an already-known DFG so it can travel
//! across the compat boundary.

/// A typed activity identifier: a `&'static str` newtype that names a specific
/// activity in a DFG at the type level.
///
/// `DfgActivityId` differs from the bare `String` stored inside [`DfgNode`]: it
/// is a *zero-cost* wrapper intended for code that must name a specific activity
/// at compile time (e.g. a test fixture, a hard-coded process template) rather
/// than build one from runtime data.
///
/// Structure-only: a labeled name, not a mined entity.
///
/// ```
/// use wasm4pm_compat::dfg::DfgActivityId;
/// const SHIP: DfgActivityId = DfgActivityId::new("ship");
/// assert_eq!(SHIP.as_str(), "ship");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DfgActivityId(pub &'static str);

impl DfgActivityId {
    /// Construct a typed activity identifier from a static string.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgActivityId;
    /// let id = DfgActivityId::new("pay");
    /// assert_eq!(id.as_str(), "pay");
    /// ```
    #[must_use]
    pub const fn new(name: &'static str) -> Self {
        DfgActivityId(name)
    }

    /// The activity name.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgActivityId;
    /// assert_eq!(DfgActivityId::new("audit").as_str(), "audit");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        self.0
    }

    /// Consumes `self` and returns the underlying `&'static str`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgActivityId;
    /// assert_eq!(DfgActivityId::new("pay").into_inner(), "pay");
    /// ```
    #[inline]
    #[must_use]
    pub const fn into_inner(self) -> &'static str {
        self.0
    }

    /// Borrows the underlying `&'static str`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgActivityId;
    /// assert_eq!(DfgActivityId::new("pay").as_inner(), "pay");
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_inner(&self) -> &'static str {
        self.0
    }
}

impl From<&'static str> for DfgActivityId {
    /// Wraps a static string as a [`DfgActivityId`]. Infallible.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgActivityId;
    /// let id: DfgActivityId = "pay".into();
    /// assert_eq!(id.as_str(), "pay");
    /// ```
    #[inline]
    fn from(s: &'static str) -> Self {
        DfgActivityId(s)
    }
}

impl AsRef<str> for DfgActivityId {
    /// Borrows the activity name as a `&str`.
    #[inline]
    fn as_ref(&self) -> &str {
        self.0
    }
}

impl core::fmt::Display for DfgActivityId {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.0)
    }
}

// ── Typed endpoint role markers ───────────────────────────────────────────────

/// A zero-sized type-level marker asserting that a type parameter plays the
/// **source** role in a directed DFG edge.
///
/// `DfgSourceMarker` and [`DfgTargetMarker`] are phantom-data tags used with
/// [`DfgTypedEdge`] to make the directionality of an edge visible to the
/// compiler. Code that accepts a source activity but not a target activity can
/// bound on [`IsDfgSource`].
///
/// Structure-only: carries no data, no graph semantics.
///
/// ```
/// use wasm4pm_compat::dfg::{DfgSourceMarker, IsDfgSource};
/// fn source_slot<S: IsDfgSource>() {}
/// source_slot::<DfgSourceMarker>();
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct DfgSourceMarker;

/// A zero-sized type-level marker asserting that a type parameter plays the
/// **target** role in a directed DFG edge.
///
/// Paired with [`DfgSourceMarker`]; see its documentation.
///
/// ```
/// use wasm4pm_compat::dfg::{DfgTargetMarker, IsDfgTarget};
/// fn target_slot<T: IsDfgTarget>() {}
/// target_slot::<DfgTargetMarker>();
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct DfgTargetMarker;

mod dfg_endpoint_seal {
    pub trait SourceSeal {}
    pub trait TargetSeal {}
    impl SourceSeal for super::DfgSourceMarker {}
    impl TargetSeal for super::DfgTargetMarker {}
}

/// Sealed trait — only [`DfgSourceMarker`] is a DFG source endpoint kind.
///
/// ```
/// use wasm4pm_compat::dfg::{DfgSourceMarker, IsDfgSource};
/// fn needs_source<S: IsDfgSource>(_: S) {}
/// needs_source(DfgSourceMarker);
/// ```
pub trait IsDfgSource: dfg_endpoint_seal::SourceSeal {}
impl IsDfgSource for DfgSourceMarker {}

/// Sealed trait — only [`DfgTargetMarker`] is a DFG target endpoint kind.
///
/// ```
/// use wasm4pm_compat::dfg::{DfgTargetMarker, IsDfgTarget};
/// fn needs_target<T: IsDfgTarget>(_: T) {}
/// needs_target(DfgTargetMarker);
/// ```
pub trait IsDfgTarget: dfg_endpoint_seal::TargetSeal {}
impl IsDfgTarget for DfgTargetMarker {}

/// A directly-follows frequency weight on a [`DfgEdge`].
///
/// A zero-cost `#[repr(transparent)]` wrapper over a `u64` count. Negative
/// frequencies are impossible by construction; the
/// [`DfgRefusal::NegativeWeight`] law exists for boundaries that admit
/// weights from signed external representations.
///
/// Structure-only: it is a labeled count, not a mined statistic.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct DfgWeight(pub u64);

impl DfgWeight {
    /// The underlying frequency count.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgWeight;
    /// assert_eq!(DfgWeight(7).count(), 7);
    /// ```
    pub fn count(self) -> u64 {
        self.0
    }

    /// Convert this `DfgWeight` into a [`DfgFrequency`] (a semantically named
    /// alias for the same count).
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgWeight, DfgFrequency};
    /// assert_eq!(DfgWeight(3).into_frequency(), DfgFrequency(3));
    /// ```
    #[must_use]
    pub fn into_frequency(self) -> DfgFrequency {
        DfgFrequency(self.0)
    }
}

/// A DFG node: a single activity in the directly-follows graph.
///
/// Holds the activity name. An empty name is refused as
/// [`DfgRefusal::MissingActivity`] at validation time.
///
/// Structure-only: a labeled vertex.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct DfgNode {
    activity: String,
}

impl DfgNode {
    /// Construct a DFG node for an activity.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgNode;
    /// assert_eq!(DfgNode::new("ship").activity(), "ship");
    /// ```
    pub fn new(activity: impl Into<String>) -> Self {
        DfgNode {
            activity: activity.into(),
        }
    }

    /// The node's activity name.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgNode;
    /// assert_eq!(DfgNode::new("a").activity(), "a");
    /// ```
    pub fn activity(&self) -> &str {
        &self.activity
    }
}

/// A DFG edge: a directly-follows relation `from → to` with a [`DfgWeight`].
///
/// An edge whose endpoints are not declared nodes is refused as
/// [`DfgRefusal::DanglingEdge`].
///
/// Structure-only: a weighted directed edge, not a mined dependency.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DfgEdge {
    from: String,
    to: String,
    weight: DfgWeight,
}

impl DfgEdge {
    /// Construct a directly-follows edge `from → to` with a frequency.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdge;
    /// let e = DfgEdge::new("a", "b", 3);
    /// assert_eq!(e.from(), "a");
    /// assert_eq!(e.to(), "b");
    /// assert_eq!(e.weight().count(), 3);
    /// ```
    pub fn new(from: impl Into<String>, to: impl Into<String>, weight: u64) -> Self {
        DfgEdge {
            from: from.into(),
            to: to.into(),
            weight: DfgWeight(weight),
        }
    }

    /// The source activity.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdge;
    /// assert_eq!(DfgEdge::new("a", "b", 1).from(), "a");
    /// ```
    pub fn from(&self) -> &str {
        &self.from
    }

    /// The target activity.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdge;
    /// assert_eq!(DfgEdge::new("a", "b", 1).to(), "b");
    /// ```
    pub fn to(&self) -> &str {
        &self.to
    }

    /// The directly-follows frequency weight.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdge;
    /// assert_eq!(DfgEdge::new("a", "b", 5).weight().count(), 5);
    /// ```
    pub fn weight(&self) -> DfgWeight {
        self.weight
    }
}

/// A directly-follows graph: nodes (activities) and weighted directly-follows
/// edges.
///
/// [`Dfg::validate`] checks *graph* shape only (non-empty, named activities,
/// edges between declared nodes). It does **not** discover the graph — that
/// graduates to `wasm4pm`.
///
/// Structure-only: an admitted `Dfg` is an interchange value, not a discovery
/// result computed here.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Dfg {
    nodes: Vec<DfgNode>,
    edges: Vec<DfgEdge>,
}

impl Dfg {
    /// Construct a DFG from nodes and edges.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{Dfg, DfgNode, DfgEdge};
    /// let g = Dfg::new(
    ///     [DfgNode::new("a"), DfgNode::new("b")],
    ///     [DfgEdge::new("a", "b", 4)],
    /// );
    /// assert!(g.validate().is_ok());
    /// ```
    pub fn new(
        nodes: impl IntoIterator<Item = DfgNode>,
        edges: impl IntoIterator<Item = DfgEdge>,
    ) -> Self {
        Dfg {
            nodes: nodes.into_iter().collect(),
            edges: edges.into_iter().collect(),
        }
    }

    /// The DFG nodes (activities).
    pub fn nodes(&self) -> &[DfgNode] {
        &self.nodes
    }

    /// The DFG edges (directly-follows relations).
    pub fn edges(&self) -> &[DfgEdge] {
        &self.edges
    }

    /// Structurally validate the DFG graph shape.
    ///
    /// Checks, in order:
    /// - the graph is non-empty ([`DfgRefusal::EmptyGraph`]);
    /// - every node names a non-empty activity ([`DfgRefusal::MissingActivity`]);
    /// - every edge connects two declared nodes ([`DfgRefusal::DanglingEdge`]).
    ///
    /// Weights are non-negative by construction; [`DfgRefusal::NegativeWeight`]
    /// and [`DfgRefusal::DiscoveryRequired`] are boundary laws for admission and
    /// graduation, not produced by this structural check. This is a shape check,
    /// not discovery.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{Dfg, DfgNode, DfgEdge, DfgRefusal};
    /// // Edge to undeclared node "ghost".
    /// let g = Dfg::new([DfgNode::new("a")], [DfgEdge::new("a", "ghost", 1)]);
    /// assert_eq!(g.validate(), Err(DfgRefusal::DanglingEdge));
    /// ```
    #[must_use = "check the shape-check result"]
    pub fn validate(&self) -> Result<(), DfgRefusal> {
        use std::collections::HashSet;
        if self.nodes.is_empty() {
            return Err(DfgRefusal::EmptyGraph);
        }
        let mut acts: HashSet<&str> = HashSet::new();
        for n in &self.nodes {
            if n.activity().is_empty() {
                return Err(DfgRefusal::MissingActivity);
            }
            acts.insert(n.activity());
        }
        for e in &self.edges {
            if !acts.contains(e.from()) || !acts.contains(e.to()) {
                return Err(DfgRefusal::DanglingEdge);
            }
        }
        Ok(())
    }
}

/// The specific, named laws under which DFG structure is refused.
///
/// Each variant cites a distinct law — never a bare "invalid input".
/// [`DfgRefusal::DiscoveryRequired`] is the boundary law that keeps discovery
/// out of this crate: a DFG that must be *discovered* (e.g. requested from an
/// empty graph as if mining had occurred) is refused here and graduates to
/// `wasm4pm`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DfgRefusal {
    /// A node names an empty activity.
    MissingActivity,
    /// A weight admitted from a signed external source was negative.
    NegativeWeight,
    /// An edge references an undeclared node.
    DanglingEdge,
    /// The graph has no nodes.
    EmptyGraph,
    /// Discovery is required to produce this DFG; it cannot be synthesized here.
    /// Graduate to `wasm4pm`.
    DiscoveryRequired,
    /// An [`ObjectCentricDfg`] declares two DFGs for the same object type.
    ///
    /// The per-type map must be injective: each object type names exactly one DFG.
    /// A duplicate registration is refused under this law.
    InconsistentObjectType,
}

impl core::fmt::Display for DfgRefusal {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let law = match self {
            DfgRefusal::MissingActivity => "MissingActivity",
            DfgRefusal::NegativeWeight => "NegativeWeight",
            DfgRefusal::DanglingEdge => "DanglingEdge",
            DfgRefusal::EmptyGraph => "EmptyGraph",
            DfgRefusal::DiscoveryRequired => "DiscoveryRequired",
            DfgRefusal::InconsistentObjectType => "InconsistentObjectType",
        };
        write!(f, "DFG refused by law: {law}")
    }
}

/// A named frequency count on a DFG edge — a semantically distinct alias for
/// [`DfgWeight`] that makes the carrier's meaning explicit at call sites.
///
/// `DfgFrequency` is the number of times one activity directly follows another
/// across the traces (or objects) in the log. It is zero-cost over a `u64`.
///
/// Structure-only: it is a labeled count, not a mined statistic.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct DfgFrequency(pub u64);

impl DfgFrequency {
    /// The underlying frequency count.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgFrequency;
    /// assert_eq!(DfgFrequency(12).count(), 12);
    /// ```
    #[must_use]
    pub fn count(self) -> u64 {
        self.0
    }

    /// Convert from a [`DfgWeight`] (the two are structurally identical).
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgFrequency, DfgWeight};
    /// assert_eq!(DfgFrequency::from_weight(DfgWeight(5)).count(), 5);
    /// ```
    #[must_use]
    pub fn from_weight(w: DfgWeight) -> Self {
        DfgFrequency(w.0)
    }

    /// Convert this `DfgFrequency` into a [`DfgWeight`] (the inverse of
    /// [`DfgFrequency::from_weight`]).
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgFrequency, DfgWeight};
    /// assert_eq!(DfgFrequency(8).into_weight(), DfgWeight(8));
    /// ```
    #[must_use]
    pub fn into_weight(self) -> DfgWeight {
        DfgWeight(self.0)
    }
}

/// A mean-duration annotation on a DFG edge, in nanoseconds.
///
/// `DfgDuration` records the mean time between one activity's completion and the
/// next activity's start, across the directly-follows pairs in the log. It is
/// zero-cost over an `i64` (negative durations are representable for admission
/// of externally-sourced data; the boundary law is
/// [`DfgRefusal::NegativeWeight`]).
///
/// Structure-only: it is a labeled duration, not a mined performance metric.
/// Performance mining (median, percentile, histogram) graduates to `wasm4pm`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct DfgDuration(pub i64);

impl DfgDuration {
    /// The duration in nanoseconds.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgDuration;
    /// assert_eq!(DfgDuration(1_000_000).ns(), 1_000_000);
    /// ```
    #[must_use]
    pub fn ns(self) -> i64 {
        self.0
    }

    /// Returns `true` if this duration is strictly negative.
    ///
    /// A negative duration is representable (for admission of external signed
    /// data) but should be refused by [`DfgRefusal::NegativeWeight`] at the
    /// boundary.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgDuration;
    /// assert!(DfgDuration(-1).is_negative());
    /// assert!(!DfgDuration(0).is_negative());
    /// assert!(!DfgDuration(42).is_negative());
    /// ```
    #[must_use]
    pub fn is_negative(self) -> bool {
        self.0 < 0
    }

    /// Convert a non-negative nanosecond count into a `DfgDuration`, or return
    /// `None` if the value is negative (boundary admission helper).
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgDuration;
    /// assert_eq!(DfgDuration::from_ns(500), Some(DfgDuration(500)));
    /// assert_eq!(DfgDuration::from_ns(-1),  None);
    /// ```
    #[must_use]
    pub fn from_ns(ns: i64) -> Option<Self> {
        if ns < 0 {
            None
        } else {
            Some(DfgDuration(ns))
        }
    }
}

/// A DFG edge annotated with both a [`DfgFrequency`] and an optional mean
/// [`DfgDuration`].
///
/// `DfgEdgeFull` is the performance-aware sibling of [`DfgEdge`]. It carries
/// the frequency count and, where available, the mean inter-activity duration.
/// A missing duration simply means the log did not record timestamps.
///
/// Structure-only: it is a weighted, performance-annotated directed edge, not
/// a mined result.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DfgEdgeFull {
    from: String,
    to: String,
    frequency: DfgFrequency,
    duration_ns: Option<DfgDuration>,
}

impl DfgEdgeFull {
    /// Construct a frequency-only (no duration) edge.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgEdgeFull, DfgFrequency};
    /// let e = DfgEdgeFull::new("a", "b", 7);
    /// assert_eq!(e.frequency().count(), 7);
    /// assert!(e.duration_ns().is_none());
    /// ```
    pub fn new(from: impl Into<String>, to: impl Into<String>, freq: u64) -> Self {
        DfgEdgeFull {
            from: from.into(),
            to: to.into(),
            frequency: DfgFrequency(freq),
            duration_ns: None,
        }
    }

    /// Attach a mean duration. Builder-style.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgEdgeFull, DfgDuration};
    /// let e = DfgEdgeFull::new("a", "b", 3).with_duration_ns(500_000);
    /// assert_eq!(e.duration_ns(), Some(DfgDuration(500_000)));
    /// ```
    pub fn with_duration_ns(mut self, ns: i64) -> Self {
        self.duration_ns = Some(DfgDuration(ns));
        self
    }

    /// The source activity.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdgeFull;
    /// assert_eq!(DfgEdgeFull::new("a", "b", 1).from(), "a");
    /// ```
    pub fn from(&self) -> &str {
        &self.from
    }

    /// The target activity.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdgeFull;
    /// assert_eq!(DfgEdgeFull::new("a", "b", 1).to(), "b");
    /// ```
    pub fn to(&self) -> &str {
        &self.to
    }

    /// The directly-follows frequency.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgEdgeFull, DfgFrequency};
    /// assert_eq!(DfgEdgeFull::new("a", "b", 4).frequency(), DfgFrequency(4));
    /// ```
    pub fn frequency(&self) -> DfgFrequency {
        self.frequency
    }

    /// The optional mean inter-activity duration.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdgeFull;
    /// assert!(DfgEdgeFull::new("a", "b", 1).duration_ns().is_none());
    /// ```
    #[must_use]
    pub fn duration_ns(&self) -> Option<DfgDuration> {
        self.duration_ns
    }
}

/// A directly-follows edge whose **direction** is enforced at the type level via
/// phantom source and target role markers.
///
/// `DfgTypedEdge<S, T>` is the compile-time-safe sibling of [`DfgEdge`]. The
/// type parameters `S` and `T` must satisfy [`IsDfgSource`] and [`IsDfgTarget`]
/// respectively; in practice they are always [`DfgSourceMarker`] and
/// [`DfgTargetMarker`]. The markers are zero-cost `PhantomData` — they carry no
/// runtime data but prevent accidentally swapping the source and target roles
/// when constructing edge tables.
///
/// Structure-only: a typed directed edge. No discovery, no token semantics.
///
/// ```
/// use wasm4pm_compat::dfg::{DfgTypedEdge, DfgSourceMarker, DfgTargetMarker, DfgWeight};
/// let edge: DfgTypedEdge<DfgSourceMarker, DfgTargetMarker> =
///     DfgTypedEdge::new("a", "b", 5);
/// assert_eq!(edge.from(), "a");
/// assert_eq!(edge.to(), "b");
/// assert_eq!(edge.weight(), DfgWeight(5));
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DfgTypedEdge<S: IsDfgSource, T: IsDfgTarget> {
    from: String,
    to: String,
    weight: DfgWeight,
    _src: core::marker::PhantomData<S>,
    _tgt: core::marker::PhantomData<T>,
}

impl<S: IsDfgSource, T: IsDfgTarget> DfgTypedEdge<S, T> {
    /// Construct a typed directed DFG edge with a frequency weight.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgTypedEdge, DfgSourceMarker, DfgTargetMarker};
    /// let e = DfgTypedEdge::<DfgSourceMarker, DfgTargetMarker>::new("place", "pay", 3);
    /// assert_eq!(e.from(), "place");
    /// assert_eq!(e.to(), "pay");
    /// ```
    pub fn new(from: impl Into<String>, to: impl Into<String>, weight: u64) -> Self {
        DfgTypedEdge {
            from: from.into(),
            to: to.into(),
            weight: DfgWeight(weight),
            _src: core::marker::PhantomData,
            _tgt: core::marker::PhantomData,
        }
    }

    /// The source activity name.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgTypedEdge, DfgSourceMarker, DfgTargetMarker};
    /// assert_eq!(DfgTypedEdge::<DfgSourceMarker, DfgTargetMarker>::new("a", "b", 1).from(), "a");
    /// ```
    pub fn from(&self) -> &str {
        &self.from
    }

    /// The target activity name.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgTypedEdge, DfgSourceMarker, DfgTargetMarker};
    /// assert_eq!(DfgTypedEdge::<DfgSourceMarker, DfgTargetMarker>::new("a", "b", 1).to(), "b");
    /// ```
    pub fn to(&self) -> &str {
        &self.to
    }

    /// The directly-follows frequency weight.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgTypedEdge, DfgSourceMarker, DfgTargetMarker, DfgWeight};
    /// assert_eq!(
    ///     DfgTypedEdge::<DfgSourceMarker, DfgTargetMarker>::new("a", "b", 9).weight(),
    ///     DfgWeight(9)
    /// );
    /// ```
    pub fn weight(&self) -> DfgWeight {
        self.weight
    }

    /// Erase the typed markers and produce a plain [`DfgEdge`].
    ///
    /// Useful when a downstream API requires [`DfgEdge`] but the edge was
    /// constructed via the typed interface.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{DfgTypedEdge, DfgSourceMarker, DfgTargetMarker};
    /// let typed = DfgTypedEdge::<DfgSourceMarker, DfgTargetMarker>::new("a", "b", 2);
    /// let plain = typed.into_edge();
    /// assert_eq!(plain.from(), "a");
    /// ```
    pub fn into_edge(self) -> DfgEdge {
        DfgEdge {
            from: self.from,
            to: self.to,
            weight: self.weight,
        }
    }
}

/// A typed object-type label for use in [`ObjectCentricDfg`] construction.
///
/// `DfgObjectType` is a zero-cost `&'static str` newtype that names a specific
/// object type in an object-centric DFG at compile time (e.g. a test fixture or
/// a hard-coded OC-process template). It is the OC-DFG counterpart of
/// [`DfgActivityId`]: both exist to make fixture code self-documenting and to
/// prevent bare-string confusion between object types and activity names.
///
/// Structure-only: a labeled name, not a mined entity.
///
/// ```
/// use wasm4pm_compat::dfg::DfgObjectType;
/// const ORDER: DfgObjectType = DfgObjectType::new("order");
/// assert_eq!(ORDER.as_str(), "order");
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DfgObjectType(pub &'static str);

impl DfgObjectType {
    /// Construct a typed object-type label from a static string.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgObjectType;
    /// let t = DfgObjectType::new("item");
    /// assert_eq!(t.as_str(), "item");
    /// ```
    #[must_use]
    pub const fn new(name: &'static str) -> Self {
        DfgObjectType(name)
    }

    /// The object type name.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgObjectType;
    /// assert_eq!(DfgObjectType::new("delivery").as_str(), "delivery");
    /// ```
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        self.0
    }

    /// Consumes `self` and returns the underlying `&'static str`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgObjectType;
    /// assert_eq!(DfgObjectType::new("order").into_inner(), "order");
    /// ```
    #[inline]
    #[must_use]
    pub const fn into_inner(self) -> &'static str {
        self.0
    }

    /// Borrows the underlying `&'static str`.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgObjectType;
    /// assert_eq!(DfgObjectType::new("order").as_inner(), "order");
    /// ```
    #[inline]
    #[must_use]
    pub const fn as_inner(&self) -> &'static str {
        self.0
    }
}

impl From<&'static str> for DfgObjectType {
    /// Wraps a static string as a [`DfgObjectType`]. Infallible.
    ///
    /// # Examples
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgObjectType;
    /// let t: DfgObjectType = "order".into();
    /// assert_eq!(t.as_str(), "order");
    /// ```
    #[inline]
    fn from(s: &'static str) -> Self {
        DfgObjectType(s)
    }
}

impl AsRef<str> for DfgObjectType {
    /// Borrows the object-type name as a `&str`.
    #[inline]
    fn as_ref(&self) -> &str {
        self.0
    }
}

impl core::fmt::Display for DfgObjectType {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.0)
    }
}

/// A per-object-type DFG: one [`Dfg`] (with frequency and optional duration
/// annotations) for each declared object type in an OCEL log.
///
/// Object-centric process mining uses one DFG per object type, not a single
/// flat graph. `ObjectCentricDfg` is the structure-only carrier for that set of
/// graphs. It does **not** discover the DFGs — discovery graduates to `wasm4pm`.
///
/// Structure-only: it holds a labelled map of DFGs, nothing more.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ObjectCentricDfg {
    /// Per-object-type DFGs: `(object_type, dfg)` pairs.
    ///
    /// Using a `Vec` (not a `HashMap`) to keep the type `Eq + Clone` without
    /// a dependency on `std::collections`. Order is by insertion.
    pub per_type: Vec<(String, Dfg)>,
}

impl ObjectCentricDfg {
    /// Construct an empty object-centric DFG set.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::ObjectCentricDfg;
    /// assert!(ObjectCentricDfg::new().per_type.is_empty());
    /// ```
    pub fn new() -> Self {
        ObjectCentricDfg::default()
    }

    /// Add or replace the DFG for the given object type. Builder-style.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{ObjectCentricDfg, Dfg, DfgNode, DfgEdge};
    /// let oc = ObjectCentricDfg::new().with_type_dfg(
    ///     "order",
    ///     Dfg::new([DfgNode::new("place"), DfgNode::new("pay")], [DfgEdge::new("place", "pay", 3)]),
    /// );
    /// assert_eq!(oc.per_type.len(), 1);
    /// ```
    pub fn with_type_dfg(mut self, object_type: impl Into<String>, dfg: Dfg) -> Self {
        self.per_type.push((object_type.into(), dfg));
        self
    }

    /// Look up the DFG for a given object type, if present.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{ObjectCentricDfg, Dfg, DfgNode};
    /// let oc = ObjectCentricDfg::new()
    ///     .with_type_dfg("order", Dfg::new([DfgNode::new("a")], []));
    /// assert!(oc.get("order").is_some());
    /// assert!(oc.get("item").is_none());
    /// ```
    #[must_use]
    pub fn get(&self, object_type: &str) -> Option<&Dfg> {
        self.per_type
            .iter()
            .find(|(t, _)| t == object_type)
            .map(|(_, d)| d)
    }

    /// The object types for which a DFG has been registered.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{ObjectCentricDfg, Dfg, DfgNode};
    /// let oc = ObjectCentricDfg::new()
    ///     .with_type_dfg("order", Dfg::new([DfgNode::new("a")], []));
    /// assert_eq!(oc.object_types().collect::<Vec<_>>(), vec!["order"]);
    /// ```
    pub fn object_types(&self) -> impl Iterator<Item = &str> {
        self.per_type.iter().map(|(t, _)| t.as_str())
    }

    /// Structurally validate all per-type DFGs and the OC-DFG map itself.
    ///
    /// Checks, in order:
    /// - no object type is registered more than once
    ///   ([`DfgRefusal::InconsistentObjectType`]);
    /// - every individual per-type [`Dfg`] passes [`Dfg::validate`].
    ///
    /// An empty `ObjectCentricDfg` (no registered types) passes — "no types
    /// known" is a valid initial state, distinct from an individual empty
    /// [`Dfg`] (which is refused as [`DfgRefusal::EmptyGraph`]).
    ///
    /// ```
    /// use wasm4pm_compat::dfg::{ObjectCentricDfg, Dfg, DfgNode, DfgEdge, DfgRefusal};
    ///
    /// // Valid: two object types, each with a non-empty DFG.
    /// let oc = ObjectCentricDfg::new()
    ///     .with_type_dfg("order", Dfg::new([DfgNode::new("place"), DfgNode::new("pay")],
    ///                                      [DfgEdge::new("place", "pay", 2)]))
    ///     .with_type_dfg("item",  Dfg::new([DfgNode::new("pick"), DfgNode::new("ship")],
    ///                                      [DfgEdge::new("pick", "ship", 5)]));
    /// assert!(oc.validate_all().is_ok());
    ///
    /// // Duplicate object type is refused.
    /// let dup = ObjectCentricDfg::new()
    ///     .with_type_dfg("order", Dfg::new([DfgNode::new("a")], []))
    ///     .with_type_dfg("order", Dfg::new([DfgNode::new("b")], []));
    /// assert_eq!(dup.validate_all(), Err(DfgRefusal::InconsistentObjectType));
    /// ```
    #[must_use = "check the shape-check result"]
    pub fn validate_all(&self) -> Result<(), DfgRefusal> {
        use std::collections::HashSet;
        let mut seen: HashSet<&str> = HashSet::new();
        for (object_type, dfg) in &self.per_type {
            if !seen.insert(object_type.as_str()) {
                return Err(DfgRefusal::InconsistentObjectType);
            }
            dfg.validate()?;
        }
        Ok(())
    }
}

/// A typed (from, to) activity pair used as a deduplication key for DFG edges.
///
/// When building a [`Dfg`] from multiple traces, the same `(from, to)` pair may
/// appear many times. `DfgEdgeKey` is the canonical key type for accumulating
/// frequencies: use it as the key in a `HashMap<DfgEdgeKey, DfgFrequency>`
/// before constructing the final [`DfgEdge`] list.
///
/// `DfgEdgeKey` is a value type: `(from, to)` — equal keys are the same
/// directly-follows pair regardless of frequency.
///
/// Structure-only: an equality-comparable pair of activity names.
///
/// ```
/// use wasm4pm_compat::dfg::DfgEdgeKey;
/// let k1 = DfgEdgeKey::new("a", "b");
/// let k2 = DfgEdgeKey::new("a", "b");
/// let k3 = DfgEdgeKey::new("b", "a");
/// assert_eq!(k1, k2);
/// assert_ne!(k1, k3);
/// assert_eq!(k1.from(), "a");
/// assert_eq!(k1.to(), "b");
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct DfgEdgeKey {
    from: String,
    to: String,
}

impl DfgEdgeKey {
    /// Construct a DFG edge key from a (from, to) activity pair.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdgeKey;
    /// let k = DfgEdgeKey::new("place", "pay");
    /// assert_eq!(k.from(), "place");
    /// assert_eq!(k.to(), "pay");
    /// ```
    pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
        DfgEdgeKey {
            from: from.into(),
            to: to.into(),
        }
    }

    /// The source activity name.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdgeKey;
    /// assert_eq!(DfgEdgeKey::new("a", "b").from(), "a");
    /// ```
    pub fn from(&self) -> &str {
        &self.from
    }

    /// The target activity name.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdgeKey;
    /// assert_eq!(DfgEdgeKey::new("a", "b").to(), "b");
    /// ```
    pub fn to(&self) -> &str {
        &self.to
    }

    /// Produce a [`DfgEdge`] by pairing this key with a frequency count.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgEdgeKey;
    /// let edge = DfgEdgeKey::new("a", "b").into_edge(5);
    /// assert_eq!(edge.weight().count(), 5);
    /// ```
    pub fn into_edge(self, weight: u64) -> DfgEdge {
        DfgEdge {
            from: self.from,
            to: self.to,
            weight: DfgWeight(weight),
        }
    }
}

// ── Van der Aalst mined DFG ───────────────────────────────────────────────────
//
// Van der Aalst (2016) §7.2: "Process Mining: Data Science in Action"
// The directly-follows relation ›_L and its frequency counters are the
// substrate of every discovery algorithm. This section provides:
//
//   DirectlyFollowsGraph  — the mined DFG value (data, not algorithm)
//   DfgMiner              — incremental accumulator: feeds traces, emits DFG
//
// DFG *discovery* (reading an EventLog, iterating traces) stays in `wasm4pm`.
// These types are the DATA CONTRACT that discovery algorithms fill and
// conformance algorithms consume.

use std::collections::HashMap;

/// A mined directly-follows graph as defined by van der Aalst (2016 §7.2).
///
/// Formally: `(Σ, →_L, #_Σ(L), start_L, end_L)` where
/// - `Σ`         = set of activities
/// - `→_L`       = directly-follows relation (present as a key in `arcs`)
/// - `#_Σ(L)`    = activity frequency function
/// - `start_L`   = start-activity frequency function
/// - `end_L`     = end-activity frequency function
///
/// This is the *discovery result* — the value that DFG mining algorithms
/// produce. It is distinct from [`Dfg`], which is the *structural* type used
/// for conformance checking (shape only, no frequencies).
///
/// ## Construction
///
/// Build via [`DfgMiner`]:
///
/// ```
/// use wasm4pm_compat::dfg::{DfgMiner, DirectlyFollowsGraph};
///
/// let mut miner = DfgMiner::new();
/// miner.record_trace(&["register", "check", "approve"]);
/// miner.record_trace(&["register", "reject"]);
/// let dfg = miner.build();
///
/// assert_eq!(dfg.activity_count("register"), 2);
/// assert_eq!(dfg.arc_count("register", "check"), 1);
/// assert_eq!(dfg.start_count("register"), 2);
/// assert_eq!(dfg.end_count("approve"), 1);
/// assert_eq!(dfg.end_count("reject"), 1);
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DirectlyFollowsGraph {
    /// Activity occurrence frequencies: `#_Σ(L)` — how often each activity
    /// appeared across all traces.
    pub activities: HashMap<String, u64>,
    /// Directly-follows arc frequencies: for each `(a, b) ∈ →_L`, how often
    /// `b` directly followed `a` in a trace.
    pub arcs: HashMap<(String, String), u64>,
    /// Start activity frequencies: `start_L(a)` — how often activity `a`
    /// was the first activity in a trace.
    pub start_activities: HashMap<String, u64>,
    /// End activity frequencies: `end_L(a)` — how often activity `a` was
    /// the last activity in a trace.
    pub end_activities: HashMap<String, u64>,
    /// Number of traces processed.
    pub trace_count: u64,
}

impl DirectlyFollowsGraph {
    /// Construct an empty DFG (zero traces, no activities or arcs).
    ///
    /// Prefer [`DfgMiner`] for incremental construction from traces.
    pub fn empty() -> Self {
        Self::default()
    }

    /// Activity occurrence count (0 if not present).
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgMiner;
    /// let dfg = DfgMiner::from_traces([&["A", "B"][..]]);
    /// assert_eq!(dfg.activity_count("A"), 1);
    /// assert_eq!(dfg.activity_count("X"), 0);
    /// ```
    pub fn activity_count(&self, activity: &str) -> u64 {
        self.activities.get(activity).copied().unwrap_or(0)
    }

    /// Directly-follows arc frequency (`a → b`). 0 if the arc does not exist.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgMiner;
    /// let dfg = DfgMiner::from_traces([&["A", "B", "B"][..]]);
    /// assert_eq!(dfg.arc_count("A", "B"), 1);
    /// assert_eq!(dfg.arc_count("B", "B"), 1);
    /// assert_eq!(dfg.arc_count("B", "A"), 0);
    /// ```
    pub fn arc_count(&self, from: &str, to: &str) -> u64 {
        self.arcs
            .get(&(from.to_string(), to.to_string()))
            .copied()
            .unwrap_or(0)
    }

    /// How often `activity` started a trace.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgMiner;
    /// let dfg = DfgMiner::from_traces([&["A", "B"][..], &["A", "C"][..]]);
    /// assert_eq!(dfg.start_count("A"), 2);
    /// assert_eq!(dfg.start_count("B"), 0);
    /// ```
    pub fn start_count(&self, activity: &str) -> u64 {
        self.start_activities.get(activity).copied().unwrap_or(0)
    }

    /// How often `activity` ended a trace.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgMiner;
    /// let dfg = DfgMiner::from_traces([&["A", "B"][..], &["A", "C"][..]]);
    /// assert_eq!(dfg.end_count("B"), 1);
    /// assert_eq!(dfg.end_count("C"), 1);
    /// assert_eq!(dfg.end_count("A"), 0);
    /// ```
    pub fn end_count(&self, activity: &str) -> u64 {
        self.end_activities.get(activity).copied().unwrap_or(0)
    }

    /// Whether arc `a → b` exists in the directly-follows relation.
    ///
    /// Van der Aalst (2016): `a >_L b` iff `arc_count(a, b) > 0`.
    pub fn follows(&self, from: &str, to: &str) -> bool {
        self.arc_count(from, to) > 0
    }

    /// Causality: `a → b` if `a >_L b` and NOT `b >_L a`.
    ///
    /// Van der Aalst's α-algorithm (2004): the causal relation used to
    /// identify sequential pairs in the Alpha algorithm.
    pub fn causes(&self, a: &str, b: &str) -> bool {
        self.follows(a, b) && !self.follows(b, a)
    }

    /// Parallel: `a || b` if `a >_L b` AND `b >_L a`.
    ///
    /// Van der Aalst's α-algorithm (2004): parallel activities that can
    /// co-occur and thus appear in both orders.
    pub fn parallel(&self, a: &str, b: &str) -> bool {
        self.follows(a, b) && self.follows(b, a)
    }

    /// Choice: `a # b` (exclusive) if NOT `a >_L b` AND NOT `b >_L a`.
    ///
    /// Van der Aalst's α-algorithm (2004): activities that never directly
    /// follow each other are in exclusive choice.
    pub fn exclusive(&self, a: &str, b: &str) -> bool {
        !self.follows(a, b) && !self.follows(b, a)
    }

    /// Sorted activity names for deterministic iteration.
    pub fn activities_sorted(&self) -> Vec<&str> {
        let mut v: Vec<&str> = self.activities.keys().map(String::as_str).collect();
        v.sort_unstable();
        v
    }

    /// Convert to the structural [`Dfg`] shape (for conformance checking).
    ///
    /// Frequency information is preserved in arc weights; start/end activities
    /// and per-node frequencies are dropped (structural shape only).
    /// Returns `None` if the DFG is empty (no activities).
    pub fn to_structural_dfg(&self) -> Option<Dfg> {
        if self.activities.is_empty() {
            return None;
        }
        let nodes: Vec<DfgNode> = {
            let mut names: Vec<&str> = self.activities.keys().map(String::as_str).collect();
            names.sort_unstable();
            names.iter().map(|a| DfgNode::new(*a)).collect()
        };
        let edges: Vec<DfgEdge> = {
            let mut arcs: Vec<_> = self.arcs.iter().collect();
            arcs.sort_unstable_by_key(|((f, t), _)| (f.as_str(), t.as_str()));
            arcs.iter()
                .map(|((f, t), &w)| DfgEdge::new(f.as_str(), t.as_str(), w))
                .collect()
        };
        Some(Dfg::new(nodes, edges))
    }
}

// ─────────────────────────────────────────────────────────────────────────────

/// Incremental DFG miner — van der Aalst's directly-follows extraction operator.
///
/// Processes traces one at a time, maintaining running frequency counts for
/// activities, arcs, start activities, and end activities. This is the
/// O(|L|) inner loop of Algorithm 7.1 in van der Aalst (2016).
///
/// ## Usage
///
/// ```
/// use wasm4pm_compat::dfg::DfgMiner;
///
/// let mut miner = DfgMiner::new();
/// miner.record_trace(&["A", "B", "C"]);
/// miner.record_trace(&["A", "C"]);
/// let dfg = miner.build();
///
/// assert_eq!(dfg.trace_count, 2);
/// assert_eq!(dfg.activity_count("A"), 2);
/// assert_eq!(dfg.arc_count("A", "B"), 1);
/// assert_eq!(dfg.arc_count("A", "C"), 1);
/// assert_eq!(dfg.start_count("A"), 2);
/// assert_eq!(dfg.end_count("C"), 2);
/// ```
#[derive(Debug, Default)]
pub struct DfgMiner {
    dfg: DirectlyFollowsGraph,
}

impl DfgMiner {
    /// Create a new miner with zero traces recorded.
    pub fn new() -> Self {
        Self::default()
    }

    /// Process a single trace and update all frequency counters.
    ///
    /// This is O(|trace|): one pass that updates activity counts, arc counts,
    /// start activity, and end activity. Empty traces are silently skipped.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgMiner;
    /// let mut m = DfgMiner::new();
    /// m.record_trace(&["A", "B"]);
    /// m.record_trace(&["A", "B"]);
    /// let dfg = m.build();
    /// assert_eq!(dfg.arc_count("A", "B"), 2);
    /// ```
    pub fn record_trace(&mut self, activities: &[impl AsRef<str>]) {
        if activities.is_empty() {
            return;
        }
        self.dfg.trace_count += 1;

        // Start activity
        *self
            .dfg
            .start_activities
            .entry(activities[0].as_ref().to_string())
            .or_insert(0) += 1;

        // End activity
        *self
            .dfg
            .end_activities
            .entry(activities[activities.len() - 1].as_ref().to_string())
            .or_insert(0) += 1;

        // Activity counts + directly-follows arcs (single O(n) pass)
        for i in 0..activities.len() {
            let a = activities[i].as_ref();
            *self.dfg.activities.entry(a.to_string()).or_insert(0) += 1;
            if i + 1 < activities.len() {
                let b = activities[i + 1].as_ref();
                *self
                    .dfg
                    .arcs
                    .entry((a.to_string(), b.to_string()))
                    .or_insert(0) += 1;
            }
        }
    }

    /// Number of traces recorded so far.
    pub fn trace_count(&self) -> u64 {
        self.dfg.trace_count
    }

    /// Borrow the accumulated DFG without consuming the miner.
    pub fn as_dfg(&self) -> &DirectlyFollowsGraph {
        &self.dfg
    }

    /// Consume the miner and return the final [`DirectlyFollowsGraph`].
    pub fn build(self) -> DirectlyFollowsGraph {
        self.dfg
    }

    /// Discover a DFG from a collection of activity-sequence traces in one call.
    ///
    /// Each item in `traces` is an iterable of activity names. This is the
    /// standard entry point for DFG discovery in `wasm4pm`; the miner is a
    /// lower-level building block for streaming and incremental use cases.
    ///
    /// ```
    /// use wasm4pm_compat::dfg::DfgMiner;
    ///
    /// let dfg = DfgMiner::from_traces([
    ///     vec!["register", "check", "approve"],
    ///     vec!["register", "reject"],
    /// ]);
    /// assert_eq!(dfg.trace_count, 2);
    /// assert_eq!(dfg.activity_count("register"), 2);
    /// assert_eq!(dfg.arc_count("register", "check"), 1);
    /// assert_eq!(dfg.arc_count("register", "reject"), 1);
    /// assert_eq!(dfg.start_count("register"), 2);
    /// assert_eq!(dfg.end_count("approve"), 1);
    /// assert_eq!(dfg.end_count("reject"), 1);
    /// ```
    pub fn from_traces<I, T, S>(traces: I) -> DirectlyFollowsGraph
    where
        I: IntoIterator<Item = T>,
        T: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut miner = Self::new();
        for trace in traces {
            let acts: Vec<S> = trace.into_iter().collect();
            miner.record_trace(&acts);
        }
        miner.build()
    }
}