edge-core 0.13.0

Transport-agnostic routing, service-adapter trait, and WebSocket client shared between the native edge-agent binary and other device hosts (iOS, future targets).
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
//! Routing engine: applies a device input primitive against the active
//! mappings to produce zero or more `(service_type, target, intent)` triples.

use std::collections::HashMap;

use tokio::sync::RwLock;
use uuid::Uuid;
use weave_contracts::{DeviceCycle, FeedbackRule, Mapping, Route, TargetCandidate};

use super::intent::{InputPrimitive, Intent};

/// A concrete intent destined for a specific service target.
#[derive(Debug, Clone)]
pub struct RoutedIntent {
    pub service_type: String,
    pub service_target: String,
    pub intent: Intent,
}

/// Per-(device_type, device_id) transient state used by target-selection
/// mode. Keyed off the mapping that declared `target_switch_on`. While
/// this struct is in `RoutingEngine::selection`, the device has entered
/// mode: `Rotate` browses `cursor`, `Press` commits, any other input
/// cancels.
#[derive(Debug, Clone)]
pub struct SelectionMode {
    pub mapping_id: Uuid,
    pub edge_id: String,
    pub candidates: Vec<TargetCandidate>,
    pub cursor: usize,
    /// Accumulated rotation delta since the last cursor step. Nuimo emits
    /// rotation events at the characteristic update rate — each encoder
    /// tick is ~1/2650 of a full turn — so a "one tick = one candidate"
    /// policy skips through the whole list on a light nudge. The
    /// accumulator turns that into "one candidate per `SELECTION_ROTATION_STEP`
    /// radians-fraction of travel" so the selection ramp is legible at
    /// hardware rotation speeds.
    rotation_accumulator: f64,
}

/// Fraction of a full Nuimo turn required to advance the selection
/// cursor by one candidate. `1.0` = one full 360° turn; `0.25` = a
/// quarter turn. Tuned experimentally: for the typical 2-4 candidate
/// case this gives roughly one candidate per thumb-flick, versus the
/// pre-damping behaviour where a finger slip cycled through every
/// candidate in the list.
pub const SELECTION_ROTATION_STEP: f64 = 0.25;

impl SelectionMode {
    pub fn new(
        mapping_id: Uuid,
        edge_id: String,
        candidates: Vec<TargetCandidate>,
        cursor: usize,
    ) -> Self {
        Self {
            mapping_id,
            edge_id,
            candidates,
            cursor,
            rotation_accumulator: 0.0,
        }
    }

    fn current(&self) -> &TargetCandidate {
        &self.candidates[self.cursor]
    }

    /// Add `delta` to the rotation accumulator and advance the cursor by
    /// one candidate for each full `SELECTION_ROTATION_STEP` worth of
    /// accumulated travel. Returns `true` if the cursor moved — callers
    /// use this to suppress redundant LED redraws for sub-threshold
    /// rotations.
    fn advance(&mut self, delta: f64) -> bool {
        let n = self.candidates.len();
        if n == 0 {
            return false;
        }
        self.rotation_accumulator += delta;
        let mut moved = false;
        while self.rotation_accumulator >= SELECTION_ROTATION_STEP {
            self.cursor = (self.cursor + 1) % n;
            self.rotation_accumulator -= SELECTION_ROTATION_STEP;
            moved = true;
        }
        while self.rotation_accumulator <= -SELECTION_ROTATION_STEP {
            self.cursor = (self.cursor + n - 1) % n;
            self.rotation_accumulator += SELECTION_ROTATION_STEP;
            moved = true;
        }
        moved
    }
}

/// One outcome of routing a single input primitive. `Normal` is the
/// existing "route to zero or more intents" path; the other variants are
/// target-selection side effects that the caller must translate into LED
/// feedback or a server-bound `SwitchTarget` frame.
#[derive(Debug, Clone)]
pub enum RouteOutcome {
    Normal(Vec<RoutedIntent>),
    /// Device just entered selection mode; show `glyph` on the LED.
    EnterSelection {
        edge_id: String,
        mapping_id: Uuid,
        glyph: String,
    },
    /// Device still in selection mode, cursor moved; show `glyph`.
    UpdateSelection {
        mapping_id: Uuid,
        glyph: String,
    },
    /// Device committed the selection; caller sends
    /// `EdgeToServer::SwitchTarget` and optionally clears the LED.
    CommitSelection {
        edge_id: String,
        mapping_id: Uuid,
        service_target: String,
    },
    /// Device exited selection mode without committing (non-rotate/press
    /// input). Caller should clear any lingering LED feedback.
    CancelSelection {
        mapping_id: Uuid,
    },
    /// Cycle gesture matched on a device with a DeviceCycle. Caller updates
    /// active locally (the engine has already done so) and sends
    /// `EdgeToServer::SwitchActiveConnection` so the server can persist
    /// and broadcast to peer edges + the web UI.
    CycleSwitch {
        device_type: String,
        device_id: String,
        active_mapping_id: Uuid,
    },
}

/// Thread-safe registry of currently-active mappings, keyed by
/// `(device_type, device_id)` for O(1) lookup per input event.
#[derive(Default)]
pub struct RoutingEngine {
    by_device: RwLock<HashMap<(String, String), Vec<Mapping>>>,
    selection: RwLock<HashMap<(String, String), SelectionMode>>,
    /// Device-level cycles. When present for `(device_type, device_id)`,
    /// `route()` filters mappings to the cycle's `active_mapping_id`
    /// (other cycle members + non-cycle mappings on that device sit
    /// dormant), and inputs matching `cycle_gesture` short-circuit to a
    /// `CycleSwitch` outcome that advances active locally and asks the
    /// caller to inform the server.
    cycles: RwLock<HashMap<(String, String), DeviceCycle>>,
}

impl RoutingEngine {
    pub fn new() -> Self {
        Self::default()
    }

    /// Replace all mappings with the provided set. Used on `config_full` push.
    pub async fn replace_all(&self, mappings: Vec<Mapping>) {
        let mut by_device: HashMap<(String, String), Vec<Mapping>> = HashMap::new();
        for m in mappings {
            by_device
                .entry((m.device_type.clone(), m.device_id.clone()))
                .or_default()
                .push(m);
        }
        *self.by_device.write().await = by_device;
    }

    /// Insert or replace one mapping, keyed by `mapping_id`. Used on
    /// `config_patch` upsert.
    pub async fn upsert_mapping(&self, mapping: Mapping) {
        let mut guard = self.by_device.write().await;
        // Remove any prior entry with the same mapping_id, regardless of
        // device key (handles device reassignment).
        for list in guard.values_mut() {
            list.retain(|m| m.mapping_id != mapping.mapping_id);
        }
        guard
            .entry((mapping.device_type.clone(), mapping.device_id.clone()))
            .or_default()
            .push(mapping);
    }

    /// Remove any mapping with the given `mapping_id`. Used on
    /// `config_patch` delete.
    pub async fn remove_mapping(&self, id: &uuid::Uuid) {
        let mut guard = self.by_device.write().await;
        for list in guard.values_mut() {
            list.retain(|m| &m.mapping_id != id);
        }
        // Prune empty device buckets so route() stays tight.
        guard.retain(|_, list| !list.is_empty());
    }

    /// Snapshot every mapping currently held, grouped or not. Used to
    /// persist the local cache after an incremental patch.
    pub async fn snapshot(&self) -> Vec<Mapping> {
        self.by_device
            .read()
            .await
            .values()
            .flatten()
            .cloned()
            .collect()
    }

    /// Replace all device cycles. Used on `config_full` push.
    pub async fn replace_cycles(&self, cycles: Vec<DeviceCycle>) {
        let mut map: HashMap<(String, String), DeviceCycle> = HashMap::new();
        for c in cycles {
            map.insert((c.device_type.clone(), c.device_id.clone()), c);
        }
        *self.cycles.write().await = map;
    }

    /// Insert or replace a device cycle. Used on `device_cycle_patch` upsert.
    pub async fn upsert_cycle(&self, cycle: DeviceCycle) {
        let key = (cycle.device_type.clone(), cycle.device_id.clone());
        self.cycles.write().await.insert(key, cycle);
    }

    /// Remove a device's cycle. Used on `device_cycle_patch` delete.
    pub async fn remove_cycle(&self, device_type: &str, device_id: &str) -> bool {
        let key = (device_type.to_string(), device_id.to_string());
        self.cycles.write().await.remove(&key).is_some()
    }

    /// Update only the active mapping ID for an existing cycle. Returns
    /// false if no cycle exists or `active_mapping_id` is not in the
    /// cycle's `mapping_ids` list.
    pub async fn set_cycle_active(
        &self,
        device_type: &str,
        device_id: &str,
        active_mapping_id: Uuid,
    ) -> bool {
        let key = (device_type.to_string(), device_id.to_string());
        let mut cycles = self.cycles.write().await;
        let Some(cycle) = cycles.get_mut(&key) else {
            return false;
        };
        if !cycle.mapping_ids.contains(&active_mapping_id) {
            return false;
        }
        cycle.active_mapping_id = Some(active_mapping_id);
        true
    }

    /// Snapshot every cycle. Used to persist the local cache.
    pub async fn cycles_snapshot(&self) -> Vec<DeviceCycle> {
        self.cycles.read().await.values().cloned().collect()
    }

    /// If `input` matches the cycle gesture for the device's `DeviceCycle`,
    /// advance `active_mapping_id` to the next entry locally and return
    /// the new active id. Otherwise return `None` and leave state untouched.
    ///
    /// Callers (Nuimo / Tap Dial event loops on every platform) should
    /// invoke this BEFORE `route()`. When it returns `Some(id)`, skip the
    /// normal routing dispatch and instead emit
    /// `EdgeToServer::SwitchActiveConnection { ..., active_mapping_id: id }`
    /// so the server can persist + broadcast. This keeps cycle-gesture
    /// detection at the engine layer (already correct) while leaving
    /// callers free to use either `route()` or `route_with_mode()` for
    /// non-gesture inputs.
    pub async fn try_cycle_switch(
        &self,
        device_type: &str,
        device_id: &str,
        input: &InputPrimitive,
    ) -> Option<Uuid> {
        let key = (device_type.to_string(), device_id.to_string());
        let cycle = self.cycles.read().await.get(&key).cloned()?;
        let gesture = cycle.cycle_gesture.as_deref()?;
        if !input.matches_route(gesture) {
            return None;
        }
        let next = next_active(&cycle)?;
        self.cycles
            .write()
            .await
            .entry(key)
            .and_modify(|c| c.active_mapping_id = Some(next));
        Some(next)
    }

    /// Fetch a cycle by device key, if any.
    pub async fn cycle_for(&self, device_type: &str, device_id: &str) -> Option<DeviceCycle> {
        let key = (device_type.to_string(), device_id.to_string());
        self.cycles.read().await.get(&key).cloned()
    }

    /// Feedback rules attached to whichever mapping covers the given
    /// `(service_type, target)` — either as its primary target or as a
    /// listed candidate (including candidates that override the mapping's
    /// `service_type`). Returns an empty vec when no mapping covers the
    /// target, letting the caller fall back to hardcoded defaults.
    ///
    /// Feedback is stored at the mapping level (all candidates share one
    /// rule set), so a candidate match still returns the mapping's
    /// `feedback`.
    pub async fn feedback_rules_for_target(
        &self,
        service_type: &str,
        target: &str,
    ) -> Vec<FeedbackRule> {
        let guard = self.by_device.read().await;
        for list in guard.values() {
            if let Some(rules) = mapping_rules_for_target(list, service_type, target) {
                return rules;
            }
        }
        Vec::new()
    }

    /// Same as `feedback_rules_for_target` but scoped to one `(device_type,
    /// device_id)` bucket. Use this from per-device feedback pumps so a
    /// Nuimo only reacts when the state change belongs to a mapping it
    /// owns — otherwise a second Nuimo mapped elsewhere would flash glyphs
    /// for unrelated service activity.
    ///
    /// Returns `None` when no mapping on this device covers
    /// `(service_type, target)` — the caller should skip. Returns
    /// `Some(vec)` when a mapping exists; the vec may be empty, which
    /// signals "mapping exists but user configured no rules — fall back
    /// to hardcoded defaults" (preserves single-device behavior).
    pub async fn feedback_rules_for_device_target(
        &self,
        device_type: &str,
        device_id: &str,
        service_type: &str,
        target: &str,
    ) -> Option<Vec<FeedbackRule>> {
        let guard = self.by_device.read().await;
        let list = guard.get(&(device_type.to_string(), device_id.to_string()))?;
        mapping_rules_for_target(list, service_type, target)
    }

    /// Find every device whose mapping owns `(service_type, target)` and
    /// return its `(device_type, device_id, feedback_rules)`. Used by the
    /// iOS feedback pump, which fans a single state update out to every
    /// LED that should display it — typically 1 device, but two Nuimos
    /// paired to the same iPad both deserve feedback.
    pub async fn feedback_targets_for(
        &self,
        service_type: &str,
        target: &str,
    ) -> Vec<(String, String, Vec<FeedbackRule>)> {
        let guard = self.by_device.read().await;
        let mut out = Vec::new();
        for ((device_type, device_id), list) in guard.iter() {
            if let Some(rules) = mapping_rules_for_target(list, service_type, target) {
                out.push((device_type.clone(), device_id.clone(), rules));
            }
        }
        out
    }

    /// Apply the given input primitive from a specific device, returning every
    /// intent it produces across all matching mappings.
    ///
    /// When the device has a `DeviceCycle`, only the mapping identified
    /// by `active_mapping_id` is eligible — non-active members and
    /// non-member mappings on the same device sit dormant. Cycle-gesture
    /// inputs are NOT short-circuited here (they would silently dispatch
    /// nothing); use `route_with_mode` to surface a `CycleSwitch` outcome.
    pub async fn route(
        &self,
        device_type: &str,
        device_id: &str,
        input: &InputPrimitive,
    ) -> Vec<RoutedIntent> {
        let key = (device_type.to_string(), device_id.to_string());
        let cycle = self.cycles.read().await.get(&key).cloned();
        let guard = self.by_device.read().await;
        let Some(mappings) = guard.get(&key) else {
            return Vec::new();
        };
        let active_filter = active_filter_from_cycle(cycle.as_ref());
        route_mappings(mappings, input, active_filter)
    }

    /// Same dispatch as `route`, but also implements:
    /// - the device-level Cycle: cycle-gesture inputs short-circuit to a
    ///   `CycleSwitch` outcome (active is advanced locally; caller relays
    ///   to server). When a cycle exists, only the active mapping fires.
    /// - the legacy `target_switch_on` + `target_candidates` selection
    ///   mode for backward compat — only consulted when no cycle exists
    ///   for the device.
    pub async fn route_with_mode(
        &self,
        device_type: &str,
        device_id: &str,
        input: &InputPrimitive,
    ) -> RouteOutcome {
        let key = (device_type.to_string(), device_id.to_string());

        // Cycle path: takes precedence over legacy selection mode.
        // If the input matches `cycle_gesture`, advance active locally
        // and return a CycleSwitch outcome. Otherwise apply the active
        // filter to mapping routing.
        {
            let cycles = self.cycles.read().await;
            if let Some(cycle) = cycles.get(&key).cloned() {
                drop(cycles);
                if let Some(gesture) = cycle.cycle_gesture.as_deref() {
                    if input.matches_route(gesture) {
                        // Compute next active without holding the read
                        // lock through the write.
                        let next = next_active(&cycle);
                        if let Some(next_id) = next {
                            // Advance local state; engine is the source
                            // of truth until server confirms.
                            self.cycles
                                .write()
                                .await
                                .entry(key.clone())
                                .and_modify(|c| {
                                    c.active_mapping_id = Some(next_id);
                                });
                            return RouteOutcome::CycleSwitch {
                                device_type: device_type.to_string(),
                                device_id: device_id.to_string(),
                                active_mapping_id: next_id,
                            };
                        }
                    }
                }
                // Non-cycle-gesture input on a cycled device: filter
                // to the active mapping and route normally. Skip the
                // legacy selection-mode path entirely — devices on
                // the cycle model don't enter selection mode.
                let active_filter = active_filter_from_cycle(Some(&cycle));
                let guard = self.by_device.read().await;
                let Some(mappings) = guard.get(&key) else {
                    return RouteOutcome::Normal(Vec::new());
                };
                return RouteOutcome::Normal(route_mappings(mappings, input, active_filter));
            }
        }

        // Already in selection mode for this device: intercept rotate /
        // press / cancel before dispatching to normal routing.
        {
            let mut sel = self.selection.write().await;
            if let Some(mode) = sel.get_mut(&key) {
                match input {
                    InputPrimitive::Rotate { delta } => {
                        // Sub-threshold rotations accumulate without
                        // emitting UpdateSelection — the LED keeps the
                        // current candidate's glyph and no log line
                        // fires until the cursor actually moves.
                        if !mode.advance(*delta) {
                            return RouteOutcome::Normal(Vec::new());
                        }
                        let glyph = mode.current().glyph.clone();
                        let mapping_id = mode.mapping_id;
                        return RouteOutcome::UpdateSelection { mapping_id, glyph };
                    }
                    InputPrimitive::Press => {
                        let mapping_id = mode.mapping_id;
                        let service_target = mode.current().target.clone();
                        let edge_id = mode.edge_id.clone();
                        sel.remove(&key);
                        return RouteOutcome::CommitSelection {
                            edge_id,
                            mapping_id,
                            service_target,
                        };
                    }
                    _ => {
                        let mapping_id = mode.mapping_id;
                        sel.remove(&key);
                        return RouteOutcome::CancelSelection { mapping_id };
                    }
                }
            }
        }

        // Not in mode yet: check whether this input should enter mode on
        // any mapping for this device, else fall through to normal routing.
        let guard = self.by_device.read().await;
        let Some(mappings) = guard.get(&key) else {
            return RouteOutcome::Normal(Vec::new());
        };

        for m in mappings {
            if !m.active {
                continue;
            }
            let Some(switch_on) = m.target_switch_on.as_deref() else {
                continue;
            };
            if m.target_candidates.is_empty() {
                continue;
            }
            if !input.matches_route(switch_on) {
                continue;
            }
            // Enter mode with cursor one step AFTER the current
            // service_target — so swipe_up→press (no rotate) cycles to
            // the next candidate. Rotate still browses from there.
            let current_idx = m
                .target_candidates
                .iter()
                .position(|c| c.target == m.service_target);
            let cursor = match current_idx {
                Some(i) => (i + 1) % m.target_candidates.len(),
                None => 0,
            };
            let mode = SelectionMode::new(
                m.mapping_id,
                m.edge_id.clone(),
                m.target_candidates.clone(),
                cursor,
            );
            let glyph = mode.current().glyph.clone();
            let mapping_id = mode.mapping_id;
            let edge_id = mode.edge_id.clone();
            drop(guard);
            self.selection.write().await.insert(key, mode);
            return RouteOutcome::EnterSelection {
                edge_id,
                mapping_id,
                glyph,
            };
        }

        RouteOutcome::Normal(route_mappings(mappings, input, None))
    }
}

/// Compute the next active mapping ID in the cycle order. Returns `None`
/// when the cycle is empty or its current `active_mapping_id` does not
/// match any entry (caller may want to reset to head, but this helper
/// stays conservative).
fn next_active(cycle: &DeviceCycle) -> Option<Uuid> {
    if cycle.mapping_ids.is_empty() {
        return None;
    }
    let active = cycle.active_mapping_id?;
    let pos = cycle.mapping_ids.iter().position(|id| *id == active)?;
    let next = (pos + 1) % cycle.mapping_ids.len();
    Some(cycle.mapping_ids[next])
}

/// Extract the active filter UUID from a cycle if one exists. `None`
/// means "no cycle — all matching mappings fire" (preserves backward
/// compatibility for devices without a cycle).
fn active_filter_from_cycle(cycle: Option<&DeviceCycle>) -> Option<Uuid> {
    cycle.and_then(|c| c.active_mapping_id)
}

/// Look for a mapping in `list` whose primary `(service_type, target)` or
/// any `target_candidates` entry matches the given pair. Returns the
/// mapping's `feedback` clone on hit. `None` means no mapping covers the
/// target, letting the caller fall back to defaults.
fn mapping_rules_for_target(
    list: &[Mapping],
    service_type: &str,
    target: &str,
) -> Option<Vec<FeedbackRule>> {
    for m in list {
        if m.service_type == service_type && m.service_target == target {
            return Some(m.feedback.clone());
        }
        for c in &m.target_candidates {
            let c_service_type = c.service_type.as_deref().unwrap_or(&m.service_type);
            if c_service_type == service_type && c.target == target {
                return Some(m.feedback.clone());
            }
        }
    }
    None
}

fn route_mappings(
    mappings: &[Mapping],
    input: &InputPrimitive,
    active_filter: Option<Uuid>,
) -> Vec<RoutedIntent> {
    let mut out = Vec::new();
    for m in mappings {
        if !m.active {
            continue;
        }
        // When a cycle is in effect, only the active mapping fires.
        // Other cycle members + non-cycle mappings on this device are
        // skipped. (The cycle's mapping_ids list is enforced on the
        // active_filter side — only the active id will pass through.)
        if let Some(active_id) = active_filter {
            if m.mapping_id != active_id {
                continue;
            }
        }
        // Resolve the effective service_type + routes for the currently
        // active target. When the active target is a cross-service
        // candidate (e.g. Roon-flavoured mapping pointing at a Hue light),
        // `effective_for` returns the candidate's overrides so the
        // dispatcher sees the right adapter + intent set.
        let (service_type, routes) = m.effective_for(&m.service_target);
        for route in routes {
            if !input.matches_route(&route.input) {
                continue;
            }
            if let Some(intent) = build_intent(route, input) {
                out.push(RoutedIntent {
                    service_type: service_type.to_string(),
                    service_target: m.service_target.clone(),
                    intent,
                });
                // Only first matching route per mapping fires.
                break;
            }
        }
    }
    out
}

fn build_intent(route: &Route, input: &InputPrimitive) -> Option<Intent> {
    let damping = route
        .params
        .get("damping")
        .and_then(|v| v.as_f64())
        .unwrap_or(1.0);

    match route.intent.as_str() {
        "play" => Some(Intent::Play),
        "pause" => Some(Intent::Pause),
        "play_pause" | "playpause" => Some(Intent::PlayPause),
        "stop" => Some(Intent::Stop),
        "next" => Some(Intent::Next),
        "previous" => Some(Intent::Previous),
        "mute" => Some(Intent::Mute),
        "unmute" => Some(Intent::Unmute),
        "power_toggle" => Some(Intent::PowerToggle),
        "power_on" => Some(Intent::PowerOn),
        "power_off" => Some(Intent::PowerOff),
        "volume_change" => input
            .continuous_value()
            .map(|v| Intent::VolumeChange { delta: v * damping }),
        "volume_set" => route
            .params
            .get("value")
            .and_then(|v| v.as_f64())
            .map(|value| Intent::VolumeSet { value }),
        "seek_relative" => input.continuous_value().map(|v| Intent::SeekRelative {
            seconds: v * damping,
        }),
        "brightness_change" => input
            .continuous_value()
            .map(|v| Intent::BrightnessChange { delta: v * damping }),
        "color_temperature_change" => input
            .continuous_value()
            .map(|v| Intent::ColorTemperatureChange { delta: v * damping }),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Direction;
    use std::collections::BTreeMap;
    use uuid::Uuid;
    use weave_contracts::Route;

    fn rotate_mapping() -> Mapping {
        Mapping {
            mapping_id: Uuid::new_v4(),
            edge_id: "living-room".into(),
            device_type: "nuimo".into(),
            device_id: "C3:81:DF:4E".into(),
            service_type: "roon".into(),
            service_target: "zone-1".into(),
            routes: vec![Route {
                input: "rotate".into(),
                intent: "volume_change".into(),
                params: BTreeMap::from([("damping".into(), serde_json::json!(80.0))]),
            }],
            feedback: vec![],
            active: true,
            target_candidates: vec![],
            target_switch_on: None,
        }
    }

    #[tokio::test]
    async fn rotate_produces_volume_change_with_damping() {
        let engine = RoutingEngine::new();
        engine.replace_all(vec![rotate_mapping()]).await;

        let out = engine
            .route(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Rotate { delta: 0.03 },
            )
            .await;
        assert_eq!(out.len(), 1);
        match &out[0].intent {
            Intent::VolumeChange { delta } => assert!((*delta - 2.4).abs() < 0.001),
            other => panic!("expected VolumeChange, got {:?}", other),
        }
        assert_eq!(out[0].service_type, "roon");
        assert_eq!(out[0].service_target, "zone-1");
    }

    #[tokio::test]
    async fn inactive_mappings_are_skipped() {
        let mut m = rotate_mapping();
        m.active = false;
        let engine = RoutingEngine::new();
        engine.replace_all(vec![m]).await;

        let out = engine
            .route(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Rotate { delta: 0.03 },
            )
            .await;
        assert!(out.is_empty());
    }

    #[tokio::test]
    async fn unknown_device_returns_empty() {
        let engine = RoutingEngine::new();
        engine.replace_all(vec![rotate_mapping()]).await;

        let out = engine
            .route("nuimo", "unknown", &InputPrimitive::Rotate { delta: 0.03 })
            .await;
        assert!(out.is_empty());
    }

    fn selection_mapping() -> Mapping {
        let mut m = rotate_mapping();
        m.service_target = "target-A".into();
        m.target_switch_on = Some("swipe_up".into());
        m.target_candidates = vec![
            TargetCandidate {
                target: "target-A".into(),
                label: "A".into(),
                glyph: "glyph-a".into(),
                service_type: None,
                routes: None,
            },
            TargetCandidate {
                target: "target-B".into(),
                label: "B".into(),
                glyph: "glyph-b".into(),
                service_type: None,
                routes: None,
            },
        ];
        m
    }

    /// A mapping whose primary target is a Roon zone and whose secondary
    /// candidate is a Hue light with its own route table. Used to exercise
    /// the `effective_for` cross-service override path.
    fn cross_service_mapping() -> Mapping {
        let mut m = rotate_mapping();
        m.service_target = "roon-zone".into();
        m.target_switch_on = Some("long_press".into());
        m.target_candidates = vec![
            TargetCandidate {
                target: "roon-zone".into(),
                label: "Roon".into(),
                glyph: "roon".into(),
                service_type: None,
                routes: None,
            },
            TargetCandidate {
                target: "hue-light".into(),
                label: "Hue".into(),
                glyph: "hue".into(),
                service_type: Some("hue".into()),
                routes: Some(vec![Route {
                    input: "rotate".into(),
                    intent: "brightness_change".into(),
                    params: BTreeMap::from([("damping".into(), serde_json::json!(50.0))]),
                }]),
            },
        ];
        m
    }

    #[test]
    fn effective_for_returns_mapping_defaults_when_target_not_overridden() {
        let m = cross_service_mapping();
        let (svc, routes) = m.effective_for("roon-zone");
        assert_eq!(svc, "roon");
        assert_eq!(routes.len(), 1);
        assert_eq!(routes[0].intent, "volume_change");
    }

    #[test]
    fn effective_for_returns_candidate_overrides_when_present() {
        let m = cross_service_mapping();
        let (svc, routes) = m.effective_for("hue-light");
        assert_eq!(svc, "hue");
        assert_eq!(routes.len(), 1);
        assert_eq!(routes[0].intent, "brightness_change");
    }

    #[tokio::test]
    async fn rotate_on_cross_service_candidate_produces_hue_intent() {
        let mut m = cross_service_mapping();
        // Simulate the user having switched the active target to the Hue
        // candidate (as if selection mode had committed on it).
        m.service_target = "hue-light".into();

        let engine = RoutingEngine::new();
        engine.replace_all(vec![m]).await;

        let out = engine
            .route(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Rotate { delta: 0.1 },
            )
            .await;
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].service_type, "hue");
        assert_eq!(out[0].service_target, "hue-light");
        match &out[0].intent {
            Intent::BrightnessChange { delta } => assert!((*delta - 5.0).abs() < 0.001),
            other => panic!("expected BrightnessChange, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn swipe_up_press_cycles_to_next_target_without_rotate() {
        let engine = RoutingEngine::new();
        engine.replace_all(vec![selection_mapping()]).await;

        match engine
            .route_with_mode(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Swipe {
                    direction: Direction::Up,
                },
            )
            .await
        {
            RouteOutcome::EnterSelection { glyph, .. } => {
                // Entering mode from target-A should point at target-B.
                assert_eq!(glyph, "glyph-b");
            }
            other => panic!("expected EnterSelection, got {:?}", other),
        }

        match engine
            .route_with_mode("nuimo", "C3:81:DF:4E", &InputPrimitive::Press)
            .await
        {
            RouteOutcome::CommitSelection { service_target, .. } => {
                assert_eq!(service_target, "target-B")
            }
            other => panic!("expected CommitSelection, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn rotate_then_press_commits_advanced_candidate() {
        let engine = RoutingEngine::new();
        engine.replace_all(vec![selection_mapping()]).await;

        // Enter: cursor jumps to target-B (position 1).
        let _ = engine
            .route_with_mode(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Swipe {
                    direction: Direction::Up,
                },
            )
            .await;
        // Rotate forward past the damping threshold — wraps from B back to A.
        match engine
            .route_with_mode(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Rotate {
                    delta: SELECTION_ROTATION_STEP,
                },
            )
            .await
        {
            RouteOutcome::UpdateSelection { glyph, .. } => assert_eq!(glyph, "glyph-a"),
            other => panic!("expected UpdateSelection, got {:?}", other),
        }
        match engine
            .route_with_mode("nuimo", "C3:81:DF:4E", &InputPrimitive::Press)
            .await
        {
            RouteOutcome::CommitSelection { service_target, .. } => {
                assert_eq!(service_target, "target-A")
            }
            other => panic!("expected CommitSelection, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn sub_threshold_rotate_keeps_cursor_still() {
        let engine = RoutingEngine::new();
        engine.replace_all(vec![selection_mapping()]).await;

        // Enter selection at target-B.
        let _ = engine
            .route_with_mode(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Swipe {
                    direction: Direction::Up,
                },
            )
            .await;

        // A single small rotation accumulates but does not cross the
        // threshold. Caller sees an empty Normal outcome — no LED push,
        // no state change.
        match engine
            .route_with_mode(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Rotate {
                    delta: SELECTION_ROTATION_STEP / 2.0,
                },
            )
            .await
        {
            RouteOutcome::Normal(routed) => assert!(routed.is_empty()),
            other => panic!("expected Normal(empty), got {:?}", other),
        }

        // A second small rotation pushes the accumulator over the
        // threshold — cursor moves.
        match engine
            .route_with_mode(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Rotate {
                    delta: SELECTION_ROTATION_STEP / 2.0 + 0.01,
                },
            )
            .await
        {
            RouteOutcome::UpdateSelection { glyph, .. } => assert_eq!(glyph, "glyph-a"),
            other => panic!("expected UpdateSelection, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn large_rotate_produces_single_step_per_outcome() {
        // advance() advances until the accumulator is below the threshold,
        // but route_with_mode yields a single RouteOutcome per input event.
        // Verify a 2.4-step delta lands on a cursor position consistent
        // with two advances (not one, not four).
        let engine = RoutingEngine::new();
        engine.replace_all(vec![selection_mapping()]).await;

        let _ = engine
            .route_with_mode(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Swipe {
                    direction: Direction::Up,
                },
            )
            .await;
        // Starting cursor is at B (index 1). 2 steps forward in a 2-entry
        // list wraps back to B. Use a delta that advances exactly twice
        // to land deterministically.
        match engine
            .route_with_mode(
                "nuimo",
                "C3:81:DF:4E",
                &InputPrimitive::Rotate {
                    delta: SELECTION_ROTATION_STEP * 2.0,
                },
            )
            .await
        {
            RouteOutcome::UpdateSelection { glyph, .. } => assert_eq!(glyph, "glyph-b"),
            other => panic!("expected UpdateSelection, got {:?}", other),
        }
    }

    fn playback_glyph_rule() -> FeedbackRule {
        FeedbackRule {
            state: "playback".into(),
            feedback_type: "glyph".into(),
            mapping: serde_json::json!({
                "playing": "play",
                "paused": "pause",
                "stopped": "pause",
            }),
        }
    }

    fn mapping_with_feedback() -> Mapping {
        let mut m = rotate_mapping();
        m.feedback = vec![playback_glyph_rule()];
        m
    }

    #[tokio::test]
    async fn feedback_rules_match_primary_target() {
        let engine = RoutingEngine::new();
        engine.replace_all(vec![mapping_with_feedback()]).await;

        let rules = engine.feedback_rules_for_target("roon", "zone-1").await;
        assert_eq!(rules.len(), 1);
        assert_eq!(rules[0].state, "playback");
    }

    #[tokio::test]
    async fn feedback_rules_match_candidate_override_service_type() {
        let mut m = mapping_with_feedback();
        m.target_candidates = vec![TargetCandidate {
            target: "hue-light-1".into(),
            label: "Living".into(),
            glyph: "link".into(),
            service_type: Some("hue".into()),
            routes: None,
        }];
        let engine = RoutingEngine::new();
        engine.replace_all(vec![m]).await;

        let rules = engine.feedback_rules_for_target("hue", "hue-light-1").await;
        assert_eq!(
            rules.len(),
            1,
            "candidate with overridden service_type inherits mapping feedback",
        );
    }

    #[tokio::test]
    async fn feedback_rules_empty_for_unknown_target() {
        let engine = RoutingEngine::new();
        engine.replace_all(vec![mapping_with_feedback()]).await;

        let rules = engine
            .feedback_rules_for_target("roon", "some-other-zone")
            .await;
        assert!(rules.is_empty());
    }

    #[tokio::test]
    async fn feedback_rules_for_device_target_scopes_by_device() {
        // Two mappings for the same Roon zone, but on different Nuimos.
        // Only the device that owns the mapping should receive feedback.
        let mut m_a = mapping_with_feedback();
        m_a.device_id = "nuimo-a".into();
        let mut m_b = mapping_with_feedback();
        m_b.mapping_id = Uuid::new_v4();
        m_b.device_id = "nuimo-b".into();
        m_b.service_target = "zone-b".into();

        let engine = RoutingEngine::new();
        engine.replace_all(vec![m_a, m_b]).await;

        let rules_a = engine
            .feedback_rules_for_device_target("nuimo", "nuimo-a", "roon", "zone-1")
            .await;
        let rules_a = rules_a.expect("nuimo-a owns zone-1");
        assert_eq!(rules_a.len(), 1);

        let rules_b_wrong = engine
            .feedback_rules_for_device_target("nuimo", "nuimo-b", "roon", "zone-1")
            .await;
        assert!(
            rules_b_wrong.is_none(),
            "nuimo-b does not own zone-1 — must skip entirely",
        );

        let rules_b_right = engine
            .feedback_rules_for_device_target("nuimo", "nuimo-b", "roon", "zone-b")
            .await;
        let rules_b_right = rules_b_right.expect("nuimo-b owns zone-b");
        assert_eq!(rules_b_right.len(), 1);
    }

    #[tokio::test]
    async fn feedback_rules_for_device_target_none_for_unknown_device() {
        let engine = RoutingEngine::new();
        engine.replace_all(vec![mapping_with_feedback()]).await;

        let rules = engine
            .feedback_rules_for_device_target("nuimo", "unknown-device", "roon", "zone-1")
            .await;
        assert!(
            rules.is_none(),
            "no mapping for unknown device — caller should skip",
        );
    }

    #[tokio::test]
    async fn feedback_rules_for_device_target_some_empty_for_mapping_without_rules() {
        // A mapping exists for the device + target, but `feedback` is empty.
        // Result must be `Some(vec![])` so the caller falls back to
        // hardcoded defaults (preserves single-device behavior).
        let m = rotate_mapping(); // no feedback rules
        let engine = RoutingEngine::new();
        engine.replace_all(vec![m]).await;

        let rules = engine
            .feedback_rules_for_device_target("nuimo", "C3:81:DF:4E", "roon", "zone-1")
            .await;
        let rules = rules.expect("mapping exists — caller should fall back to defaults");
        assert!(
            rules.is_empty(),
            "no explicit rules configured — pump will use FeedbackPlan defaults",
        );
    }
}