lazily 0.44.0

Lazy reactive signals with dependency tracking and cache invalidation
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
//! Full Harel/SCXML state charts — native Rust, conforming to
//! `lazily-spec/docs/state-charts.md`.
//!
//! A chart is **compute, not protocol**: it is never serialized as a distinct
//! wire kind. In this reactive binding the active configuration lives in a
//! [`CellHandle`], so any slot/signal/effect reading [`StateChart::configuration`],
//! [`StateChart::active_leaves`], or [`StateChart::matches`] is invalidated on a
//! real transition; a no-op self-transition is suppressed by the cell's
//! `PartialEq` guard (see the spec's "Self-transitions" section).
//!
//! Implemented subset (per the spec's implementation-status note): compound
//! states, orthogonal (parallel) regions, shallow + deep history, entry/exit/
//! transition actions, named guards, external + internal transitions. Extended
//! state `{"expr": …}` guards and `run` actions are rejected explicitly; `final`
//! states are accepted as leaves without raising completion (`done`) events.

use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap};

#[cfg(feature = "thread-safe")]
use crate::ThreadSafeContext;
#[cfg(feature = "async")]
use crate::{AsyncCellHandle, AsyncContext};
use crate::{CellHandle, Context};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    Atomic,
    Compound,
    Parallel,
    History(HistoryKind),
    Final,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HistoryKind {
    Shallow,
    Deep,
}

#[derive(Debug, Clone)]
struct Transition {
    target: String,
    guard: Option<String>,
    action: Vec<String>,
    internal: bool,
}

#[derive(Debug, Clone)]
struct StateDef {
    parent: Option<String>,
    kind: Kind,
    initial: Option<String>,
    default: Option<String>,
    transitions: HashMap<String, Transition>,
    entry: Vec<String>,
    exit: Vec<String>,
}

/// A parsed, immutable chart definition.
#[derive(Debug, Clone)]
pub struct ChartDef {
    states: HashMap<String, StateDef>,
    children: HashMap<String, Vec<String>>,
    order: HashMap<String, usize>,
    depth: HashMap<String, usize>,
    root: String,
}

/// A history recording for a region exited at least once.
#[derive(Debug, Clone)]
enum Recording {
    /// Direct child of the region that was active.
    Shallow(String),
    /// Full active sub-configuration below the region (leaves + ancestors).
    Deep(BTreeSet<String>),
}

/// A reactive full-Harel state chart backed by a configuration cell.
pub struct StateChart {
    def: ChartDef,
    config: CellHandle<BTreeSet<String>>,
    history: RefCell<HashMap<String, Recording>>,
    last_actions: RefCell<Vec<String>>,
}

impl ChartDef {
    /// Parse a chart definition from a `serde_json::Value` of the declarative
    /// form. Returns an error string for malformed charts or unsupported
    /// features (`run` actions, `{"expr": …}` guards).
    #[cfg(feature = "statechart-json")]
    pub fn from_json(value: &serde_json::Value) -> Result<ChartDef, String> {
        let obj = value
            .as_object()
            .ok_or_else(|| "chart must be a JSON object".to_string())?;
        // Validates `chart.initial` is present; descent uses each compound's
        // own `initial` from the root, so the value itself is not stored.
        let _top_initial = obj
            .get("initial")
            .and_then(|v| v.as_str())
            .ok_or_else(|| "chart.initial is required".to_string())?
            .to_string();

        let states_obj = obj
            .get("states")
            .and_then(|v| v.as_object())
            .ok_or_else(|| "chart.states is required".to_string())?;

        let mut states: HashMap<String, StateDef> = HashMap::new();
        let mut order: HashMap<String, usize> = HashMap::new();
        for (idx, (id, raw)) in states_obj.iter().enumerate() {
            order.insert(id.clone(), idx);
            states.insert(id.clone(), parse_state(id, raw)?);
        }

        Self::from_states(states, order)
    }

    /// Assemble a validated [`ChartDef`] from parsed states plus their document
    /// order. Shared by [`ChartDef::from_json`] and the Rust [`ChartBuilder`], so
    /// both definition paths derive parent→children, the single parent-less root,
    /// and per-node depth identically. `order` maps each state id to the position
    /// that fixes deterministic parallel-region descent.
    fn from_states(
        states: HashMap<String, StateDef>,
        order: HashMap<String, usize>,
    ) -> Result<ChartDef, String> {
        // Derived structure: children, depth, root.
        let mut children: HashMap<String, Vec<String>> = HashMap::new();
        let mut root: Option<String> = None;
        for (id, def) in &states {
            match &def.parent {
                Some(p) => children.entry(p.clone()).or_default().push(id.clone()),
                None => {
                    if root.is_some() {
                        return Err("chart has more than one root (parent-less state)".into());
                    }
                    root = Some(id.clone());
                }
            }
        }
        // Sort children by document order for deterministic parallel descent.
        for kids in children.values_mut() {
            kids.sort_by_key(|k| order.get(k).copied().unwrap_or(usize::MAX));
        }
        let root = root.ok_or_else(|| "chart has no root (parent-less state)".to_string())?;

        let mut depth: HashMap<String, usize> = HashMap::new();
        compute_depth(&states, &root, 0, &mut depth);

        Ok(ChartDef {
            states,
            children,
            order,
            depth,
            root,
        })
    }

    fn kind(&self, id: &str) -> Kind {
        self.states.get(id).map(|s| s.kind).unwrap_or(Kind::Atomic)
    }

    fn ancestors_inclusive(&self, id: &str) -> Vec<String> {
        let mut out = Vec::new();
        let mut cur = Some(id.to_string());
        while let Some(cid) = cur {
            out.push(cid.clone());
            cur = self.states.get(&cid).and_then(|s| s.parent.clone());
        }
        out
    }

    fn lca(&self, a: &str, b: &str) -> String {
        let anc_a: std::collections::HashSet<String> =
            self.ancestors_inclusive(a).into_iter().collect();
        for cid in self.ancestors_inclusive(b) {
            if anc_a.contains(&cid) {
                return cid;
            }
        }
        self.root.clone()
    }

    fn is_proper_descendant(&self, desc: &str, anc: &str) -> bool {
        desc != anc && self.ancestors_inclusive(desc).iter().any(|x| x == anc)
    }

    fn depth(&self, id: &str) -> usize {
        self.depth.get(id).copied().unwrap_or(0)
    }
}

#[cfg(feature = "statechart-json")]
fn parse_state(id: &str, raw: &serde_json::Value) -> Result<StateDef, String> {
    let obj = raw
        .as_object()
        .ok_or_else(|| format!("state {id} must be an object"))?;
    let parent = obj.get("parent").and_then(|v| v.as_str()).map(String::from);
    let initial = obj
        .get("initial")
        .and_then(|v| v.as_str())
        .map(String::from);
    let default = obj
        .get("default")
        .and_then(|v| v.as_str())
        .map(String::from);

    if obj.get("run").is_some() {
        return Err(format!(
            "state {id} uses `run` actions, which are not supported (rejecting explicitly per spec)"
        ));
    }

    let kind = if let Some(h) = obj.get("history").and_then(|v| v.as_str()) {
        Kind::History(match h {
            "shallow" => HistoryKind::Shallow,
            "deep" => HistoryKind::Deep,
            other => return Err(format!("state {id}: unknown history kind `{other}`")),
        })
    } else if obj.get("parallel").and_then(|v| v.as_bool()) == Some(true) {
        Kind::Parallel
    } else if matches!(obj.get("kind").and_then(|v| v.as_str()), Some("final")) {
        Kind::Final
    } else if obj.contains_key("initial") {
        Kind::Compound
    } else {
        Kind::Atomic
    };

    let entry = parse_action_list(obj.get("entry"))?;
    let exit = parse_action_list(obj.get("exit"))?;

    let mut transitions = HashMap::new();
    if let Some(on) = obj.get("on").and_then(|v| v.as_object()) {
        for (event, raw_t) in on {
            transitions.insert(event.clone(), parse_transition(raw_t)?);
        }
    }

    Ok(StateDef {
        parent,
        kind,
        initial,
        default,
        transitions,
        entry,
        exit,
    })
}

#[cfg(feature = "statechart-json")]
fn parse_action_list(raw: Option<&serde_json::Value>) -> Result<Vec<String>, String> {
    match raw {
        None => Ok(Vec::new()),
        Some(serde_json::Value::Array(items)) => items
            .iter()
            .map(|v| {
                v.as_str()
                    .map(String::from)
                    .ok_or_else(|| "action must be a string".into())
            })
            .collect(),
        Some(_) => Err("entry/exit must be an array of strings".into()),
    }
}

#[cfg(feature = "statechart-json")]
fn parse_transition(raw: &serde_json::Value) -> Result<Transition, String> {
    match raw {
        serde_json::Value::String(target) => Ok(Transition {
            target: target.clone(),
            guard: None,
            action: Vec::new(),
            internal: false,
        }),
        serde_json::Value::Object(o) => {
            let target = o
                .get("target")
                .and_then(|v| v.as_str())
                .ok_or_else(|| "transition requires `target`".to_string())?
                .to_string();
            let guard = match o.get("guard") {
                None => None,
                Some(serde_json::Value::String(name)) => Some(name.clone()),
                Some(serde_json::Value::Object(_)) => {
                    return Err(
                        "context-expression `{expr: …}` guards are not supported (rejecting explicitly per spec)"
                            .into(),
                    );
                }
                Some(_) => return Err("guard must be a string".into()),
            };
            let action = parse_action_list(o.get("action"))?;
            let internal = o.get("internal").and_then(|v| v.as_bool()).unwrap_or(false);
            Ok(Transition {
                target,
                guard,
                action,
                internal,
            })
        }
        _ => Err("transition must be a string or object".into()),
    }
}

fn compute_depth(
    states: &HashMap<String, StateDef>,
    id: &str,
    current: usize,
    out: &mut HashMap<String, usize>,
) {
    out.insert(id.to_string(), current);
    let next: Vec<String> = states
        .iter()
        .filter(|(_, d)| d.parent.as_deref() == Some(id))
        .map(|(k, _)| k.clone())
        .collect();
    for child in next {
        compute_depth(states, &child, current + 1, out);
    }
}

// ---------------------------------------------------------------------------
// Typed Rust builder — define a `ChartDef` in Rust instead of (or alongside) the
// JSON form. Both paths funnel through `ChartDef::from_states`, so a chart built
// in Rust is byte-for-byte equivalent to the same chart parsed from JSON.
// ---------------------------------------------------------------------------

/// A single transition, built in Rust. Equivalent to a JSON transition object.
pub struct TransitionBuilder {
    inner: Transition,
}

impl TransitionBuilder {
    /// An external transition to `target` with no guard or actions.
    pub fn to(target: impl Into<String>) -> Self {
        Self {
            inner: Transition {
                target: target.into(),
                guard: None,
                action: Vec::new(),
                internal: false,
            },
        }
    }

    /// Attach a named boolean guard (resolved at `send` time; absent → false).
    pub fn guard(mut self, name: impl Into<String>) -> Self {
        self.inner.guard = Some(name.into());
        self
    }

    /// Append a transition action name.
    pub fn action(mut self, name: impl Into<String>) -> Self {
        self.inner.action.push(name.into());
        self
    }

    /// Mark this transition internal (no exit/re-entry of the source subtree
    /// when the target is the source or a proper descendant).
    pub fn internal(mut self) -> Self {
        self.inner.internal = true;
        self
    }
}

/// A single chart state, built in Rust. Mirrors the JSON state object.
pub struct StateBuilder {
    id: String,
    def: StateDef,
}

impl StateBuilder {
    fn with_kind(id: impl Into<String>, kind: Kind, initial: Option<String>) -> Self {
        Self {
            id: id.into(),
            def: StateDef {
                parent: None,
                kind,
                initial,
                default: None,
                transitions: HashMap::new(),
                entry: Vec::new(),
                exit: Vec::new(),
            },
        }
    }

    /// An atomic leaf state.
    pub fn atomic(id: impl Into<String>) -> Self {
        Self::with_kind(id, Kind::Atomic, None)
    }

    /// A compound state with the given initial child.
    pub fn compound(id: impl Into<String>, initial: impl Into<String>) -> Self {
        Self::with_kind(id, Kind::Compound, Some(initial.into()))
    }

    /// A parallel (orthogonal) state; all its child regions are entered together.
    pub fn parallel(id: impl Into<String>) -> Self {
        Self::with_kind(id, Kind::Parallel, None)
    }

    /// A final leaf state (accepted as a leaf; raises no completion event).
    pub fn final_state(id: impl Into<String>) -> Self {
        Self::with_kind(id, Kind::Final, None)
    }

    /// A shallow-history pseudostate for its parent region.
    pub fn history_shallow(id: impl Into<String>) -> Self {
        Self::with_kind(id, Kind::History(HistoryKind::Shallow), None)
    }

    /// A deep-history pseudostate for its parent region.
    pub fn history_deep(id: impl Into<String>) -> Self {
        Self::with_kind(id, Kind::History(HistoryKind::Deep), None)
    }

    /// Set the parent state id. Omit only for the single chart root.
    pub fn parent(mut self, parent: impl Into<String>) -> Self {
        self.def.parent = Some(parent.into());
        self
    }

    /// Set the default target used on a history pseudostate's first entry.
    pub fn default_child(mut self, target: impl Into<String>) -> Self {
        self.def.default = Some(target.into());
        self
    }

    /// Append an entry action name.
    pub fn entry(mut self, action: impl Into<String>) -> Self {
        self.def.entry.push(action.into());
        self
    }

    /// Append an exit action name.
    pub fn exit(mut self, action: impl Into<String>) -> Self {
        self.def.exit.push(action.into());
        self
    }

    /// Add an unguarded external transition on `event` to `target`.
    pub fn on(self, event: impl Into<String>, target: impl Into<String>) -> Self {
        self.on_transition(event, TransitionBuilder::to(target))
    }

    /// Add a guarded external transition on `event` to `target`.
    pub fn on_guarded(
        self,
        event: impl Into<String>,
        target: impl Into<String>,
        guard: impl Into<String>,
    ) -> Self {
        self.on_transition(event, TransitionBuilder::to(target).guard(guard))
    }

    /// Add a fully-specified transition on `event`.
    pub fn on_transition(mut self, event: impl Into<String>, t: TransitionBuilder) -> Self {
        self.def.transitions.insert(event.into(), t.inner);
        self
    }
}

/// Fluent builder assembling a [`ChartDef`] from typed Rust states, the
/// definition path parallel to [`ChartDef::from_json`]. State insertion order
/// fixes deterministic parallel-region descent, exactly as JSON key order does.
#[derive(Default)]
pub struct ChartBuilder {
    states: Vec<StateBuilder>,
}

impl ChartBuilder {
    /// A new, empty builder.
    pub fn new() -> Self {
        Self { states: Vec::new() }
    }

    /// Add a state. The first parent-less state added becomes the root.
    pub fn state(mut self, state: StateBuilder) -> Self {
        self.states.push(state);
        self
    }

    /// Validate and assemble the [`ChartDef`]. Fails on a duplicate state id, on
    /// zero or more than one parent-less root, matching the JSON path.
    pub fn build(self) -> Result<ChartDef, String> {
        let mut states: HashMap<String, StateDef> = HashMap::new();
        let mut order: HashMap<String, usize> = HashMap::new();
        for (idx, sb) in self.states.into_iter().enumerate() {
            if states.contains_key(&sb.id) {
                return Err(format!("duplicate state id `{}`", sb.id));
            }
            order.insert(sb.id.clone(), idx);
            states.insert(sb.id, sb.def);
        }
        ChartDef::from_states(states, order)
    }
}

impl StateChart {
    /// Create a chart over `ctx`, entering the initial configuration by
    /// descending from the root via each compound's `initial` (and every region
    /// for parallel states). Initial entry actions are recorded and available
    /// via [`StateChart::last_actions`].
    pub fn new(ctx: &Context, def: ChartDef) -> Self {
        let mut enter = BTreeSet::new();
        let mut actions = Vec::new();
        enter_subtree(&def, &def.root, &mut enter, &mut actions);

        let config = ctx.cell(enter);
        Self {
            def,
            config,
            history: RefCell::new(HashMap::new()),
            last_actions: RefCell::new(actions),
        }
    }

    /// Ordered action names fired by the initial entry or the most recent
    /// [`StateChart::send`] (exit → transition → entry).
    pub fn last_actions(&self) -> Vec<String> {
        self.last_actions.borrow().clone()
    }

    /// The full active configuration (active leaves plus all active ancestors).
    pub fn configuration(&self, ctx: &Context) -> BTreeSet<String> {
        ctx.get_cell(&self.config)
    }

    /// Active atomic leaves, sorted (one per parallel region; one for single-region).
    pub fn active_leaves(&self, ctx: &Context) -> Vec<String> {
        let config = self.configuration(ctx);
        let mut leaves: Vec<String> = config
            .iter()
            .filter(|id| matches!(self.def.kind(id), Kind::Atomic | Kind::Final))
            .cloned()
            .collect();
        leaves.sort();
        leaves
    }

    /// Hierarchical "state-in" predicate: `true` iff `id` is in the active configuration.
    pub fn matches(&self, ctx: &Context, id: &str) -> bool {
        self.configuration(ctx).contains(id)
    }

    /// Send an event. Returns `true` if any transition was taken, `false` if
    /// rejected (configuration unchanged, no actions fired). `guards` resolves
    /// named guards for this send (absent/unknown name → fail-closed `false`).
    pub fn send(&self, ctx: &Context, event: &str, guards: &HashMap<String, bool>) -> bool {
        let config = self.configuration(ctx);
        let mut history = self.history.borrow_mut();
        match engine_send(&self.def, &mut history, &config, event, guards) {
            Some((new_config, actions)) => {
                drop(history);
                *self.last_actions.borrow_mut() = actions;
                if new_config != config {
                    ctx.set_cell(&self.config, new_config);
                }
                true
            }
            None => {
                drop(history);
                *self.last_actions.borrow_mut() = Vec::new();
                false
            }
        }
    }
}

/// A reactive full-Harel state chart backed by a [`ThreadSafeContext`]. Same
/// chart semantics as [`StateChart`]; the configuration cell is shared safely
/// across threads and history/last-actions use a `parking_lot::Mutex`, so the
/// whole chart is `Send + Sync`. A status observer on one thread can read
/// [`ThreadSafeStateChart::configuration`] while another drives
/// [`ThreadSafeStateChart::send`].
#[cfg(feature = "thread-safe")]
pub struct ThreadSafeStateChart {
    def: ChartDef,
    config: CellHandle<BTreeSet<String>>,
    history: parking_lot::Mutex<HashMap<String, Recording>>,
    last_actions: parking_lot::Mutex<Vec<String>>,
}

#[cfg(feature = "thread-safe")]
impl ThreadSafeStateChart {
    /// Create a chart over `ctx`, entering the initial configuration.
    pub fn new(ctx: &ThreadSafeContext, def: ChartDef) -> Self {
        let mut enter = BTreeSet::new();
        let mut actions = Vec::new();
        enter_subtree(&def, &def.root, &mut enter, &mut actions);
        let config = ctx.cell(enter);
        Self {
            def,
            config,
            history: parking_lot::Mutex::new(HashMap::new()),
            last_actions: parking_lot::Mutex::new(actions),
        }
    }

    /// Ordered action names fired by the initial entry or the most recent `send`.
    pub fn last_actions(&self) -> Vec<String> {
        self.last_actions.lock().clone()
    }

    /// The full active configuration (active leaves plus all active ancestors).
    pub fn configuration(&self, ctx: &ThreadSafeContext) -> BTreeSet<String> {
        ctx.get_cell(&self.config)
    }

    /// Active atomic leaves, sorted (one per parallel region).
    pub fn active_leaves(&self, ctx: &ThreadSafeContext) -> Vec<String> {
        let config = self.configuration(ctx);
        let mut leaves: Vec<String> = config
            .iter()
            .filter(|id| matches!(self.def.kind(id), Kind::Atomic | Kind::Final))
            .cloned()
            .collect();
        leaves.sort();
        leaves
    }

    /// Hierarchical "state-in" predicate.
    pub fn matches(&self, ctx: &ThreadSafeContext, id: &str) -> bool {
        self.configuration(ctx).contains(id)
    }

    /// Send an event. Returns `true` if any transition was taken, `false` if
    /// rejected (configuration unchanged, no actions fired).
    pub fn send(
        &self,
        ctx: &ThreadSafeContext,
        event: &str,
        guards: &HashMap<String, bool>,
    ) -> bool {
        let config = self.configuration(ctx);
        let mut history = self.history.lock();
        match engine_send(&self.def, &mut history, &config, event, guards) {
            Some((new_config, actions)) => {
                drop(history);
                *self.last_actions.lock() = actions;
                if new_config != config {
                    ctx.set_cell(&self.config, new_config);
                }
                true
            }
            None => {
                drop(history);
                *self.last_actions.lock() = Vec::new();
                false
            }
        }
    }
}

/// A reactive full-Harel state chart backed by an [`AsyncContext`]. Because
/// cells are the synchronous input layer of `AsyncContext`, `send`/`state`
/// remain synchronous; reactive observers (`ctx.effect`/`ctx.signal` reading the
/// configuration) drive async recomputation. Same chart semantics as
/// [`StateChart`].
#[cfg(feature = "async")]
pub struct AsyncStateChart {
    def: ChartDef,
    config: AsyncCellHandle<BTreeSet<String>>,
    history: parking_lot::Mutex<HashMap<String, Recording>>,
    last_actions: parking_lot::Mutex<Vec<String>>,
}

#[cfg(feature = "async")]
impl AsyncStateChart {
    /// Create a chart over `ctx`, entering the initial configuration.
    pub fn new(ctx: &AsyncContext, def: ChartDef) -> Self {
        let mut enter = BTreeSet::new();
        let mut actions = Vec::new();
        enter_subtree(&def, &def.root, &mut enter, &mut actions);
        let config = ctx.cell(enter);
        Self {
            def,
            config,
            history: parking_lot::Mutex::new(HashMap::new()),
            last_actions: parking_lot::Mutex::new(actions),
        }
    }

    /// Ordered action names fired by the initial entry or the most recent `send`.
    pub fn last_actions(&self) -> Vec<String> {
        self.last_actions.lock().clone()
    }

    /// The full active configuration (active leaves plus all active ancestors).
    pub fn configuration(&self, ctx: &AsyncContext) -> BTreeSet<String> {
        ctx.get_cell(&self.config)
    }

    /// Active atomic leaves, sorted (one per parallel region).
    pub fn active_leaves(&self, ctx: &AsyncContext) -> Vec<String> {
        let config = self.configuration(ctx);
        let mut leaves: Vec<String> = config
            .iter()
            .filter(|id| matches!(self.def.kind(id), Kind::Atomic | Kind::Final))
            .cloned()
            .collect();
        leaves.sort();
        leaves
    }

    /// Hierarchical "state-in" predicate.
    pub fn matches(&self, ctx: &AsyncContext, id: &str) -> bool {
        self.configuration(ctx).contains(id)
    }

    /// Send an event (synchronous). Returns `true` if any transition was taken.
    pub fn send(&self, ctx: &AsyncContext, event: &str, guards: &HashMap<String, bool>) -> bool {
        let config = self.configuration(ctx);
        let mut history = self.history.lock();
        match engine_send(&self.def, &mut history, &config, event, guards) {
            Some((new_config, actions)) => {
                drop(history);
                *self.last_actions.lock() = actions;
                if new_config != config {
                    ctx.set_cell(&self.config, new_config);
                }
                true
            }
            None => {
                drop(history);
                *self.last_actions.lock() = Vec::new();
                false
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Context-free transition engine. Every `StateChart` variant (single-threaded,
// thread-safe, async) delegates here; only the cell storage and interior-
// mutability wrapper differ per variant, never the Harel semantics. This is the
// algorithm the spec conformance fixtures and the Lean formal model pin down —
// keep it byte-for-byte behaviourally identical across refactors.
// ---------------------------------------------------------------------------

/// Compute one Harel macrostep. Returns `Some((new_config, actions))` when a
/// transition is taken (the new configuration may equal the old for an internal
/// self-transition) and `None` when the event is rejected (no enabled
/// transition; configuration and history unchanged). `history` is mutated only
/// when a transition is actually taken.
fn engine_send(
    def: &ChartDef,
    history: &mut HashMap<String, Recording>,
    config: &BTreeSet<String>,
    event: &str,
    guards: &HashMap<String, bool>,
) -> Option<(BTreeSet<String>, Vec<String>)> {
    // 1. Enabled transitions: per active leaf, innermost passing match.
    struct Cand<'a> {
        source: String,
        transition: &'a Transition,
        leaf: String,
    }
    let mut candidates: Vec<Cand> = Vec::new();
    let leaves: Vec<String> = config
        .iter()
        .filter(|id| matches!(def.kind(id), Kind::Atomic | Kind::Final))
        .cloned()
        .collect();
    for leaf in &leaves {
        for anc in def.ancestors_inclusive(leaf) {
            if let Some(sd) = def.states.get(&anc)
                && let Some(t) = sd.transitions.get(event)
                && guard_passes(t, guards)
            {
                candidates.push(Cand {
                    source: anc.clone(),
                    transition: t,
                    leaf: leaf.clone(),
                });
                break; // innermost wins for this leaf's chain
            }
        }
    }

    if candidates.is_empty() {
        return None;
    }

    // 2. Conflict resolution: order by source depth desc, then document order;
    //    take greedily, skipping any whose exit set intersects the taken union.
    candidates.sort_by(|a, b| {
        def.depth(&b.source)
            .cmp(&def.depth(&a.source))
            .then_with(|| def.order.get(&a.source).cmp(&def.order.get(&b.source)))
    });

    let mut exit_union: BTreeSet<String> = BTreeSet::new();
    let mut enter_union: BTreeSet<String> = BTreeSet::new();
    let mut taken_transitions: Vec<&Transition> = Vec::new();
    for cand in &candidates {
        let (exit_set, enter_set) = engine_compute_exit_enter(
            def,
            history,
            &cand.source,
            cand.transition,
            &cand.leaf,
            config,
        );
        if exit_set.intersection(&exit_union).next().is_some() {
            continue; // conflicts with an already-taken transition
        }
        exit_union.extend(exit_set);
        enter_union.extend(enter_set);
        taken_transitions.push(cand.transition);
    }

    if taken_transitions.is_empty() {
        return None;
    }

    // 3. Record history for regions being exited that own a history child.
    for s in &exit_union {
        if let Some(h_child) = history_child_of(def, s) {
            record_region(def, s, h_child, config, history);
        }
    }

    // 4. Action trace: exit (innermost-first) → transition → entry (outermost-first).
    let mut actions = Vec::new();
    let mut exit_sorted: Vec<&String> = exit_union.iter().collect();
    exit_sorted.sort_by_key(|s| std::cmp::Reverse(def.depth(s)));
    for s in &exit_sorted {
        actions.extend(def.states[*s].exit.iter().cloned());
    }
    for t in &taken_transitions {
        actions.extend(t.action.iter().cloned());
    }
    let mut enter_sorted: Vec<&String> = enter_union.iter().collect();
    enter_sorted.sort_by_key(|s| def.depth(s));
    for s in &enter_sorted {
        actions.extend(def.states[*s].entry.iter().cloned());
    }

    // 5. Compute new configuration.
    let mut new_config = config.clone();
    for s in &exit_union {
        new_config.remove(s);
    }
    for s in &enter_union {
        new_config.insert(s.clone());
    }

    Some((new_config, actions))
}

fn engine_compute_exit_enter(
    def: &ChartDef,
    history: &HashMap<String, Recording>,
    source: &str,
    transition: &Transition,
    leaf: &str,
    config: &BTreeSet<String>,
) -> (BTreeSet<String>, BTreeSet<String>) {
    let target = &transition.target;
    let internal =
        transition.internal && (target == source || def.is_proper_descendant(target, source));
    let lca = if internal {
        source.to_string()
    } else {
        def.lca(leaf, target)
    };

    // Exit set: active proper-descendants of the lca.
    let exit_set: BTreeSet<String> = config
        .iter()
        .filter(|s| def.is_proper_descendant(s, &lca))
        .cloned()
        .collect();

    // Enter set.
    let mut enter: BTreeSet<String> = BTreeSet::new();
    if matches!(def.kind(target), Kind::History(_)) {
        let region = def.states[target]
            .parent
            .clone()
            .unwrap_or_else(|| def.root.clone());
        for s in path_below(def, &lca, &region) {
            enter.insert(s);
        }
        engine_restore_via_history(def, history, target, &region, &mut enter);
    } else {
        for s in path_below(def, &lca, target) {
            enter.insert(s);
        }
        let mut entry_actions = Vec::new();
        enter_subtree(def, target, &mut enter, &mut entry_actions);
    }

    (exit_set, enter)
}

fn engine_restore_via_history(
    def: &ChartDef,
    history: &HashMap<String, Recording>,
    hist: &str,
    region: &str,
    enter: &mut BTreeSet<String>,
) {
    match history.get(hist) {
        Some(Recording::Shallow(child)) => {
            let child = child.clone();
            enter.insert(child.clone());
            let mut tmp = Vec::new();
            enter_subtree(def, &child, enter, &mut tmp);
        }
        Some(Recording::Deep(set)) => {
            for s in set {
                enter.insert(s.clone());
            }
        }
        None => {
            // First entry: descend via `default`, else the region's `initial`.
            let start = def.states[hist]
                .default
                .clone()
                .or_else(|| def.states[region].initial.clone());
            if let Some(start) = start {
                for s in path_below(def, region, &start) {
                    enter.insert(s);
                }
                let mut tmp = Vec::new();
                enter_subtree(def, &start, enter, &mut tmp);
            }
        }
    }
}

fn guard_passes(t: &Transition, guards: &HashMap<String, bool>) -> bool {
    match &t.guard {
        None => true,
        Some(name) => guards.get(name).copied().unwrap_or(false), // fail-closed
    }
}

/// Enter `state` and its default descendants, recording entry actions top-down.
fn enter_subtree(
    def: &ChartDef,
    state: &str,
    enter: &mut BTreeSet<String>,
    actions: &mut Vec<String>,
) {
    enter.insert(state.to_string());
    collect_entry(def, state, actions);
    match def.kind(state) {
        Kind::Atomic | Kind::Final | Kind::History(_) => {}
        Kind::Compound => {
            if let Some(init) = def.states[state].initial.as_deref() {
                enter_subtree(def, init, enter, actions);
            }
        }
        Kind::Parallel => {
            for region in def.children.get(state).cloned().unwrap_or_default() {
                enter_subtree(def, &region, enter, actions);
            }
        }
    }
}

fn collect_entry(def: &ChartDef, state: &str, actions: &mut Vec<String>) {
    actions.extend(def.states[state].entry.iter().cloned());
}

/// Path from just-below `lca` down to `target` (exclusive lca, inclusive target).
fn path_below(def: &ChartDef, lca: &str, target: &str) -> Vec<String> {
    let mut chain = def.ancestors_inclusive(target); // [target, ..., root]
    let idx = chain.iter().position(|x| x == lca).unwrap_or(chain.len());
    chain.truncate(idx); // drop lca and above
    chain.reverse(); // [child-of-lca, ..., target]
    chain
}

fn history_child_of(def: &ChartDef, region: &str) -> Option<String> {
    def.children.get(region).and_then(|kids| {
        kids.iter()
            .find(|k| matches!(def.kind(k), Kind::History(_)))
            .cloned()
    })
}

fn record_region(
    def: &ChartDef,
    region: &str,
    hist_child: String,
    config: &BTreeSet<String>,
    history: &mut HashMap<String, Recording>,
) {
    let kind = match def.kind(&hist_child) {
        Kind::History(h) => h,
        _ => return,
    };
    match kind {
        HistoryKind::Shallow => {
            // Record the direct child of `region` that was active.
            let child = def
                .children
                .get(region)
                .cloned()
                .unwrap_or_default()
                .into_iter()
                .find(|c| config.contains(c) && !matches!(def.kind(c), Kind::History(_)));
            if let Some(c) = child {
                history.insert(hist_child, Recording::Shallow(c));
            }
        }
        HistoryKind::Deep => {
            // Record every active state strictly below `region`.
            let set: BTreeSet<String> = config
                .iter()
                .filter(|s| def.is_proper_descendant(s, region))
                .cloned()
                .collect();
            history.insert(hist_child, Recording::Deep(set));
        }
    }
}

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

    /// A small chart used by both the JSON and Rust-builder equivalence check:
    /// a parallel root over two regions, one guarded transition, one final.
    #[cfg(feature = "statechart-json")]
    fn json_chart() -> ChartDef {
        let v: serde_json::Value = serde_json::from_str(
            r#"{
              "initial": "root",
              "states": {
                "root": { "parallel": true },
                "flow": { "parent": "root", "initial": "idle" },
                "idle": { "parent": "flow", "on": { "go": { "target": "done", "guard": "ready" } } },
                "done": { "parent": "flow", "kind": "final" },
                "net": { "parent": "root", "initial": "up" },
                "up": { "parent": "net", "on": { "drop": { "target": "down" } } },
                "down": { "parent": "net", "on": { "restore": { "target": "up" } } }
              }
            }"#,
        )
        .unwrap();
        ChartDef::from_json(&v).unwrap()
    }

    fn built_chart() -> ChartDef {
        ChartBuilder::new()
            .state(StateBuilder::parallel("root"))
            .state(StateBuilder::compound("flow", "idle").parent("root"))
            .state(
                StateBuilder::atomic("idle")
                    .parent("flow")
                    .on_guarded("go", "done", "ready"),
            )
            .state(StateBuilder::final_state("done").parent("flow"))
            .state(StateBuilder::compound("net", "up").parent("root"))
            .state(StateBuilder::atomic("up").parent("net").on("drop", "down"))
            .state(
                StateBuilder::atomic("down")
                    .parent("net")
                    .on("restore", "up"),
            )
            .build()
            .unwrap()
    }

    /// The typed builder + engine are core (no feature): a built chart enters the
    /// initial configuration of every parallel region and drives a guarded edge.
    #[test]
    fn builder_engine_is_core() {
        use crate::Context;
        let ctx = Context::new();
        let chart = StateChart::new(&ctx, built_chart());
        // Both parallel regions enter their initial leaves.
        assert!(chart.matches(&ctx, "idle") && chart.matches(&ctx, "up"));
        // Guarded edge rejected when the guard is false, taken when true.
        let mut guards = HashMap::new();
        guards.insert("ready".to_string(), false);
        assert!(!chart.send(&ctx, "go", &guards));
        assert!(chart.matches(&ctx, "idle"));
        guards.insert("ready".to_string(), true);
        assert!(chart.send(&ctx, "go", &guards));
        assert!(chart.matches(&ctx, "done"));
    }

    /// The Rust builder and JSON paths produce charts that behave identically:
    /// same initial configuration and same response to the same event stream.
    #[cfg(feature = "statechart-json")]
    #[test]
    fn builder_matches_json_behaviour() {
        use crate::Context;
        let ctx_j = Context::new();
        let ctx_b = Context::new();
        let cj = StateChart::new(&ctx_j, json_chart());
        let cb = StateChart::new(&ctx_b, built_chart());
        assert_eq!(cj.configuration(&ctx_j), cb.configuration(&ctx_b));

        let mut ready = HashMap::new();
        ready.insert("ready".to_string(), false);
        // Guard false: rejected on both.
        assert_eq!(cj.send(&ctx_j, "go", &ready), cb.send(&ctx_b, "go", &ready));
        assert_eq!(cj.configuration(&ctx_j), cb.configuration(&ctx_b));
        // Orthogonal region transition on both.
        let empty = HashMap::new();
        assert!(cj.send(&ctx_j, "drop", &empty));
        assert!(cb.send(&ctx_b, "drop", &empty));
        // Guard true: accepted on both.
        ready.insert("ready".to_string(), true);
        assert!(cj.send(&ctx_j, "go", &ready));
        assert!(cb.send(&ctx_b, "go", &ready));
        assert_eq!(cj.configuration(&ctx_j), cb.configuration(&ctx_b));
        assert!(cj.matches(&ctx_j, "done") && cj.matches(&ctx_j, "down"));
    }

    #[cfg(feature = "thread-safe")]
    #[test]
    fn thread_safe_chart_is_send_sync_and_transitions() {
        use crate::ThreadSafeContext;
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<ThreadSafeStateChart>();

        let ctx = ThreadSafeContext::new();
        let chart = ThreadSafeStateChart::new(&ctx, built_chart());
        assert!(chart.matches(&ctx, "idle") && chart.matches(&ctx, "up"));
        let empty = HashMap::new();
        // Guard absent -> fail-closed rejection.
        assert!(!chart.send(&ctx, "go", &empty));
        assert!(chart.matches(&ctx, "idle"));
        let mut ready = HashMap::new();
        ready.insert("ready".to_string(), true);
        assert!(chart.send(&ctx, "go", &ready));
        assert!(chart.matches(&ctx, "done"));
    }

    #[cfg(feature = "async")]
    #[test]
    fn async_chart_transitions() {
        use crate::AsyncContext;
        let ctx = AsyncContext::new();
        let chart = AsyncStateChart::new(&ctx, built_chart());
        assert!(chart.matches(&ctx, "idle"));
        let empty = HashMap::new();
        assert!(chart.send(&ctx, "drop", &empty));
        assert!(chart.matches(&ctx, "down"));
    }
}