brinkhaustools/
monitor.rs

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
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;

use serde_json::Value;

use crate::{
    DiagParam, HeartbeatEngine, MessagePart, SelfDiagnosisEngine, Severity, ShutdownHandler,
    StatusEngine, StatusSource,
};

use crate::client::{slugify, DeviceIdentity, FleetClientConfig, FleetMonitorClient};

const DIAG_CONFIG_MISSING: u16 = 7001;
const DIAG_CONNECTION_ERROR: u16 = 7002;

/// Configuration for the StatusMonitor, typically loaded from a JSON file.
#[derive(Debug, Clone, Default)]
pub struct FleetConfig {
    pub base_url: Option<String>,
    pub broker: Option<String>,
    pub customer_name: Option<String>,
    pub machine: Option<String>,
    pub token: Option<String>,
    pub heartbeat_interval_sec: Option<u64>,
    /// Installation site (Aufstellungsort), machine-wide. `None` when the key
    /// is absent => the field is not sent (old packet format preserved).
    pub location: Option<String>,
    /// Machine-wide device identity (serial, name, inventory number, stream,
    /// password scheme). Branding is software-specific and set by the app.
    pub identity: DeviceIdentity,
}

impl FleetConfig {
    /// Load fleet config from a JSON file.
    pub fn from_file(path: &str) -> Option<Self> {
        let contents = std::fs::read_to_string(path).ok()?;
        let val: Value = serde_json::from_str(&contents).ok()?;
        let fm = val.get("fleetmanagement")?;

        Some(Self {
            base_url: fm.get("base_url").and_then(|v| v.as_str()).map(String::from),
            broker: fm.get("broker").and_then(|v| v.as_str()).map(String::from),
            customer_name: fm
                .get("customer_name")
                .and_then(|v| v.as_str())
                .map(String::from),
            machine: fm.get("machine").and_then(|v| v.as_str()).map(String::from),
            token: fm.get("token").and_then(|v| v.as_str()).map(String::from),
            heartbeat_interval_sec: fm
                .get("heartbeat_interval_sec")
                .and_then(|v| v.as_u64()),
            location: fm.get("location").and_then(|v| v.as_str()).map(String::from),
            identity: DeviceIdentity::from_fleet_json(fm),
        })
    }

    fn resolve_base_url(&self) -> String {
        if let Some(ref url) = self.base_url {
            url.clone()
        } else if let Some(ref broker) = self.broker {
            format!("https://{}", broker)
        } else {
            "https://fleet.brinkhaus-gmbh.de".to_string()
        }
    }

    fn resolve_customer(&self) -> String {
        std::env::var("STATUS_MONITOR_CUSTOMERID").unwrap_or_else(|_| {
            self.customer_name
                .as_deref()
                .unwrap_or("testCustomer")
                .to_string()
        })
    }

    fn resolve_machine(&self) -> String {
        std::env::var("STATUS_MONITOR_MACHINEID").unwrap_or_else(|_| {
            self.machine
                .as_deref()
                .unwrap_or("testMachine")
                .to_string()
        })
    }

    /// Resolve the bearer token (env `FLEET_TOKEN` > config token).
    ///
    /// Lets a container inject the secret via the environment instead of
    /// baking it into the mounted config file.
    fn resolve_token(&self) -> Option<String> {
        match std::env::var("FLEET_TOKEN") {
            Ok(t) if !t.is_empty() => Some(t),
            _ => self.token.clone(),
        }
    }
}

/// Result of a fleet command: `(result, message)`, result one of `"success"`,
/// `"failure"`, `"rejected"` (same contract as the Python `CommandResult`).
pub type CommandResult = (String, String);

type CommandHandler = Arc<dyn Fn(Option<Value>) -> CommandResult + Send + Sync>;

/// When a command is acknowledged.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AckStrategy {
    /// Acknowledge `scheduled` before running (destructive commands, restarts).
    BeforeRun,
    /// Acknowledge with the handler's result.
    AfterRun,
}

/// A command the FleetManager can invoke on this software (mirrors the Python
/// `CommandSpec`). The catalog of registered commands rides along with every
/// status snapshot under `commands`.
#[derive(Clone)]
pub struct CommandSpec {
    pub id: String,
    /// Label per language (`{"de": …, "en": …}`).
    pub label: BTreeMap<String, String>,
    pub icon: Option<String>,
    pub confirm_text: Option<BTreeMap<String, String>>,
    pub ack: AckStrategy,
    /// Issued by FleetManager workflows (e.g. licence delivery), not offered to
    /// operators as a button. Advertised as `"system": true`.
    pub system: bool,
    handler: CommandHandler,
}

impl CommandSpec {
    /// A command acknowledged after it ran. The handler gets the invocation
    /// `payload` (if any) and runs on its own thread.
    pub fn new<F>(id: &str, label: BTreeMap<String, String>, handler: F) -> Self
    where
        F: Fn(Option<Value>) -> CommandResult + Send + Sync + 'static,
    {
        Self {
            id: id.to_string(),
            label,
            icon: None,
            confirm_text: None,
            ack: AckStrategy::AfterRun,
            system: false,
            handler: Arc::new(handler),
        }
    }

    /// Mark as a system command (no operator button).
    pub fn system(mut self) -> Self {
        self.system = true;
        self
    }

    /// Acknowledge before running.
    pub fn ack_before_run(mut self) -> Self {
        self.ack = AckStrategy::BeforeRun;
        self
    }

    fn catalog_entry(&self) -> Value {
        let mut entry = serde_json::json!({ "id": self.id, "label": self.label });
        if let Some(icon) = &self.icon {
            entry["icon"] = Value::String(icon.clone());
        }
        if let Some(text) = &self.confirm_text {
            entry["confirm_text"] = serde_json::json!(text);
        }
        if self.system {
            entry["system"] = Value::Bool(true);
        }
        entry
    }
}

type CommandRegistry = Arc<RwLock<BTreeMap<String, CommandSpec>>>;
type AckQueue = Arc<Mutex<Vec<Value>>>;

fn ack(row_id: &Value, result: &str, message: &str) -> Value {
    serde_json::json!({ "id": row_id, "result": result, "message": message })
}

/// Dispatch piggybacked commands: unknown or malformed ones are rejected,
/// known ones run on their own thread so the fleet loops never block.
fn dispatch_commands(commands: Vec<Value>, registry: &CommandRegistry, acks: &AckQueue) {
    for cmd in commands {
        let row_id = cmd.get("id").cloned().unwrap_or(Value::Null);
        let command_id = cmd.get("command_id").and_then(Value::as_str).unwrap_or("");
        if row_id.is_null() || command_id.is_empty() {
            log::warn!("Ignoring malformed fleet command: {}", cmd);
            continue;
        }
        let spec = registry.read().unwrap().get(command_id).cloned();
        let Some(spec) = spec else {
            log::warn!("Unknown fleet command_id={command_id:?} (row {row_id})");
            acks.lock()
                .unwrap()
                .push(ack(&row_id, "rejected", &format!("unknown command_id: {command_id}")));
            continue;
        };
        let payload = cmd.get("payload").cloned().filter(|p| !p.is_null());
        let acks = Arc::clone(acks);
        if spec.ack == AckStrategy::BeforeRun {
            acks.lock().unwrap().push(ack(&row_id, "scheduled", "command scheduled"));
        }
        let spawned = std::thread::Builder::new()
            .name(format!("fleet-cmd-{}", spec.id))
            .spawn({
                let row_id = row_id.clone();
                let acks = Arc::clone(&acks);
                move || {
                    let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        (spec.handler)(payload)
                    }));
                    let (result, message) = outcome.unwrap_or_else(|_| {
                        log::error!("Fleet command {} panicked", spec.id);
                        ("failure".to_string(), "handler panicked".to_string())
                    });
                    if spec.ack == AckStrategy::AfterRun {
                        acks.lock().unwrap().push(ack(&row_id, &result, &message));
                    } else {
                        log::info!("Fleet command {} finished: {result} {message}", spec.id);
                    }
                }
            });
        if let Err(e) = spawned {
            log::error!("Could not spawn fleet command thread: {e}");
            acks.lock().unwrap().push(ack(&row_id, "failure", &format!("spawn failed: {e}")));
        }
    }
}

/// High-level bridge between SelfDiagnosisEngine and the FleetManager backend.
#[allow(dead_code)]
pub struct StatusMonitor {
    client: FleetMonitorClient,
    diagnosis: Option<Arc<SelfDiagnosisEngine>>,
    status_engine: Option<Arc<StatusEngine>>,
    shutdown: Option<ShutdownHandler>,
    config_path: Option<String>,
    config_loaded: AtomicBool,
    server_display: RwLock<String>,
    software_name: String,
    heartbeat_interval: Duration,
    // Controller-loop timings (overridable for tests), stored in milliseconds.
    initial_delay_ms: AtomicU64,
    controller_period_ms: AtomicU64,
    commands: CommandRegistry,
    pending_acks: AckQueue,
}

impl StatusMonitor {
    /// Create a new StatusMonitor.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        config_path: Option<&str>,
        diagnosis: Option<Arc<SelfDiagnosisEngine>>,
        software_name: &str,
        version: Option<&str>,
        shutdown: Option<ShutdownHandler>,
        status_engine: Option<Arc<StatusEngine>>,
        // Fleet-hierarchy placement (software-specific). location/Aufstellungsort
        // is read from the config file instead. All sent only when set.
        group: Option<String>,
        group_priority: Option<i64>,
        sort_priority: Option<i64>,
    ) -> Self {
        let fleet_cfg = config_path
            .and_then(FleetConfig::from_file)
            .unwrap_or_default();
        let config_loaded = config_path.is_some()
            && FleetConfig::from_file(config_path.unwrap()).is_some();

        if !config_loaded {
            if let Some(ref diag) = diagnosis {
                let path = config_path.unwrap_or("none");
                diag.notify_keyed(
                    DIAG_CONFIG_MISSING,
                    vec![MessagePart::new(
                        "diag.detail.7001.configMissing",
                        BTreeMap::from([("path".to_string(), DiagParam::Text(path.to_string()))]),
                    )],
                    &format!("FleetManager config not found: {path}"),
                    Severity::Info,
                );
            }
        } else if let Some(ref diag) = diagnosis {
            diag.clear(DIAG_CONFIG_MISSING);
        }

        let base_url = fleet_cfg.resolve_base_url();
        let customer = fleet_cfg.resolve_customer();
        let machine = fleet_cfg.resolve_machine();
        let token = fleet_cfg.resolve_token();
        let heartbeat_interval = fleet_cfg
            .heartbeat_interval_sec
            .map(Duration::from_secs)
            .unwrap_or(Duration::from_secs(60));

        let client_config = FleetClientConfig {
            base_url: base_url.clone(),
            customer: slugify(&customer),
            machine: slugify(&machine),
            software: slugify(software_name),
            token,
            heartbeat_interval,
            version: version.map(String::from),
            group,
            group_priority,
            sort_priority,
            location: fleet_cfg.location.clone(),
            identity: fleet_cfg.identity.clone(),
        };

        let client = FleetMonitorClient::new(client_config);
        let commands: CommandRegistry = Arc::default();
        let pending_acks: AckQueue = Arc::default();
        {
            let (registry, acks) = (Arc::clone(&commands), Arc::clone(&pending_acks));
            client.on_commands(move |cmds| dispatch_commands(cmds, &registry, &acks));
        }

        Self {
            client,
            diagnosis,
            status_engine,
            shutdown,
            config_path: config_path.map(String::from),
            config_loaded: AtomicBool::new(config_loaded),
            server_display: RwLock::new(base_url),
            software_name: software_name.to_string(),
            heartbeat_interval,
            initial_delay_ms: AtomicU64::new(10_000),
            controller_period_ms: AtomicU64::new(60_000),
            commands,
            pending_acks,
        }
    }

    /// Register a command the FleetManager can invoke. Replaces an earlier one
    /// with the same id; the catalog is re-sent with the next snapshot.
    pub fn register_command(&self, spec: CommandSpec) {
        log::info!("Registered fleet command: {}", spec.id);
        self.commands.write().unwrap().insert(spec.id.clone(), spec);
    }

    /// Catalog of registered commands as advertised in the status snapshot.
    pub fn command_catalog(&self) -> Vec<Value> {
        self.commands
            .read()
            .unwrap()
            .values()
            .map(CommandSpec::catalog_entry)
            .collect()
    }

    /// Licence report sent in every heartbeat (field `licence`); `None` omits it.
    pub fn set_licence(&self, report: Option<Value>) {
        self.client.set_licence(report);
    }

    /// Hardware report sent in every heartbeat (field `hardware`); `None` omits it.
    pub fn set_hardware(&self, report: Option<Value>) {
        self.client.set_hardware(report);
    }

    /// Release channel this build was delivered with (see the client).
    pub fn set_build_channel(&self, channel: Option<String>) -> Result<(), String> {
        self.client.set_build_channel(channel)
    }

    /// Release channel with its source, see the client.
    pub fn channel(&self) -> Option<(String, crate::client::ChannelSource)> {
        self.client.channel()
    }

    /// Send queued command acknowledgements; failed sends are kept for the next try.
    async fn flush_acks(&self) {
        let batch: Vec<Value> = std::mem::take(&mut *self.pending_acks.lock().unwrap());
        if batch.is_empty() {
            return;
        }
        if self.client.send_command_ack(&batch).await.is_err() {
            let mut queue = self.pending_acks.lock().unwrap();
            let newer = std::mem::take(&mut *queue);
            *queue = batch;
            queue.extend(newer);
        }
    }

    /// Mark the client as started. Prefer [`run_fleet_loops`] which also drives
    /// the heartbeat and controller loops; this only flips the lifecycle flag.
    pub fn start(&self) {
        self.client.start();
    }

    /// Stop the client (signals the background loops to exit).
    pub fn stop(&self) {
        self.client.stop();
    }

    /// Brand this software runs under (e.g. "uttec"), sent in every heartbeat.
    pub fn set_branding(&self, branding: Option<String>) {
        self.client.set_branding(branding);
    }

    /// Override the controller-loop timings. For tests only — lets a
    /// conformance test observe diagnostics/status without waiting 10s + 60s.
    pub fn set_controller_timing_for_testing(&self, initial_delay: Duration, period: Duration) {
        self.initial_delay_ms
            .store(initial_delay.as_millis() as u64, Ordering::SeqCst);
        self.controller_period_ms
            .store(period.as_millis() as u64, Ordering::SeqCst);
    }

    /// Map diagnosis messages to fleet-compatible tuples.
    pub fn map_diagnosis(&self) -> Vec<(u16, String, u8)> {
        let diag = match &self.diagnosis {
            Some(d) => d,
            None => return vec![(0, "All self tests passed".to_string(), 0)],
        };

        let status = diag.get_status();
        let messages = match status["messages"].as_array() {
            Some(msgs) if !msgs.is_empty() => msgs,
            _ => return vec![(0, "All self tests passed".to_string(), 0)],
        };

        messages
            .iter()
            .map(|msg| {
                let code = msg["code"].as_u64().unwrap_or(0) as u16;
                let text = msg["messageForUI"]
                    .as_str()
                    .unwrap_or("Unknown")
                    .to_string();
                let critical = msg["critical"].as_bool().unwrap_or(false);
                let information = msg["information"].as_bool().unwrap_or(false);
                let severity: u8 = if critical {
                    2
                } else if information {
                    0
                } else {
                    1
                };
                (code, text, severity)
            })
            .collect()
    }

    /// Update diagnosis based on connection state (wires code 7002).
    fn update_diagnosis(&self) {
        if let Some(ref diag) = self.diagnosis {
            if self.client.is_connected() {
                diag.clear(DIAG_CONNECTION_ERROR);
            } else {
                // Not critical: edges run unattended in Schaltschränke that often have no
                // (or intermittent) internet on purpose. A device unable to phone home to
                // FleetManager is expected, self-contained operation, not a device fault —
                // flagging it critical made every such edge report a permanent "critical"
                // self-diagnosis error for something the device itself is fine without.
                let error = self
                    .client
                    .last_connect_error()
                    .unwrap_or_else(|| "Not connected".to_string());
                diag.notify_keyed(
                    DIAG_CONNECTION_ERROR,
                    vec![MessagePart::new(
                        "diag.detail.7002.connection",
                        BTreeMap::from([("error".to_string(), DiagParam::Text(error.clone()))]),
                    )],
                    &format!("FleetManager: {error}"),
                    Severity::Info,
                );
            }
        }
    }

    /// Retry reading the config file if the initial load failed, then
    /// reconfigure the client (mirrors Python `_try_reload_config`).
    fn try_reload_config(&self) {
        if self.config_loaded.load(Ordering::SeqCst) {
            return;
        }
        let path = match &self.config_path {
            Some(p) => p,
            None => return,
        };
        let fleet_cfg = match FleetConfig::from_file(path) {
            Some(c) => c,
            None => return,
        };
        self.config_loaded.store(true, Ordering::SeqCst);
        if let Some(ref diag) = self.diagnosis {
            diag.clear(DIAG_CONFIG_MISSING);
        }
        let base_url = fleet_cfg.resolve_base_url();
        let customer = fleet_cfg.resolve_customer();
        let machine = fleet_cfg.resolve_machine();
        *self.server_display.write().unwrap() = base_url.clone();
        self.client
            .reconfigure(&base_url, &customer, &machine, fleet_cfg.resolve_token());
    }

    /// Derive an aggregate status string from the diagnosis system status.
    fn derive_status(&self) -> (&'static str, &'static str) {
        if let Some(ref diag) = self.diagnosis {
            let status = diag.get_status();
            if status
                .get("System Status")
                .and_then(|v| v.as_bool())
                .map(|ok| !ok)
                .unwrap_or(false)
            {
                return ("degraded", "Issues detected");
            }
        }
        ("running", "All OK")
    }

    /// Send one diagnostics + status/snapshot cycle (one controller tick).
    async fn send_diagnostics_and_status(&self) {
        let _ = self.client.send_diagnostics(&self.map_diagnosis()).await;
        let (status_str, message) = self.derive_status();
        let catalog = self.command_catalog();
        if let Some(ref engine) = self.status_engine {
            let mut snapshot = engine.get_last_status();
            if !catalog.is_empty() {
                if let Some(obj) = snapshot.as_object_mut() {
                    obj.insert("commands".to_string(), Value::Array(catalog));
                }
            }
            let _ = self
                .client
                .send_snapshot(&snapshot, Some(status_str), Some(message))
                .await;
        } else if !catalog.is_empty() {
            let snapshot = serde_json::json!({ "commands": catalog });
            let _ = self
                .client
                .send_snapshot(&snapshot, Some(status_str), Some(message))
                .await;
        } else {
            let _ = self.client.send_status(status_str, Some(message)).await;
        }
    }

    /// Run the heartbeat + controller loops until `shutdown` fires.
    ///
    /// Drives everything the Python reference does in its background threads:
    /// initial `running` status, periodic heartbeats, periodic diagnostics +
    /// status/snapshot, connection-state diagnosis (7002), config retry, and a
    /// final `stopped` status on exit.
    pub async fn run(self: Arc<Self>, shutdown: ShutdownHandler) {
        self.run_supervised(shutdown, None).await;
    }

    /// Like [`run`](Self::run), but reports to a [`HeartbeatEngine`] on every
    /// heartbeat cycle.
    ///
    /// Consumers whose architecture requires *every* long-running thread to be
    /// watchdog-supervised need this: a wedged fleet thread is otherwise silent,
    /// and silence is exactly what it is supposed to prevent. Registers with a
    /// timeout of `4 ×` the heartbeat interval — a missed beat then means
    /// "wedged", not "the fleet server is slow" (send failures are reported via
    /// diagnosis code 7002, not by withholding the beat).
    pub async fn run_supervised(
        self: Arc<Self>,
        shutdown: ShutdownHandler,
        watchdog: Option<(Arc<HeartbeatEngine>, String)>,
    ) {
        self.client.start();
        let _ = self.client.send_status("running", Some("Connected")).await;

        if let Some((engine, id)) = &watchdog {
            engine.register(id, Some(self.heartbeat_interval * 4));
        }

        let heartbeat = {
            let me = self.clone();
            let sd = shutdown.clone();
            let watchdog = watchdog.clone();
            async move {
                let interval = me.heartbeat_interval;
                loop {
                    if sd.is_shutdown() {
                        break;
                    }
                    let _ = me.client.send_heartbeat().await;
                    // Nach dem Sendeversuch, nicht nach dessen Erfolg: Ein
                    // unerreichbarer Fleetmanager ist kein hängender Thread.
                    if let Some((engine, id)) = &watchdog {
                        engine.refresh(id);
                    }
                    if interruptible_sleep(&sd, interval).await {
                        break;
                    }
                }
                if let Some((engine, id)) = &watchdog {
                    engine.cancel(id);
                }
            }
        };

        let controller = {
            let me = self.clone();
            let sd = shutdown.clone();
            async move {
                let initial =
                    Duration::from_millis(me.initial_delay_ms.load(Ordering::SeqCst));
                if interruptible_sleep(&sd, initial).await {
                    return;
                }
                loop {
                    if sd.is_shutdown() {
                        break;
                    }
                    me.try_reload_config();
                    me.update_diagnosis();
                    me.send_diagnostics_and_status().await;
                    let period =
                        Duration::from_millis(me.controller_period_ms.load(Ordering::SeqCst));
                    if interruptible_sleep(&sd, period).await {
                        break;
                    }
                }
            }
        };

        let acks = {
            let me = self.clone();
            let sd = shutdown.clone();
            async move {
                loop {
                    me.flush_acks().await;
                    if interruptible_sleep(&sd, Duration::from_millis(250)).await {
                        break;
                    }
                }
                me.flush_acks().await;
            }
        };

        tokio::join!(heartbeat, controller, acks);

        let _ = self
            .client
            .send_status("stopped", Some("Service stopped"))
            .await;
    }
}

/// Sleep up to `dur`, returning early (with `true`) if shutdown fires.
async fn interruptible_sleep(shutdown: &ShutdownHandler, dur: Duration) -> bool {
    let step = Duration::from_millis(100);
    let mut slept = Duration::ZERO;
    while slept < dur {
        if shutdown.is_shutdown() {
            return true;
        }
        let chunk = step.min(dur - slept);
        tokio::time::sleep(chunk).await;
        slept += chunk;
    }
    shutdown.is_shutdown()
}

/// Spawn the fleet heartbeat + controller loops on a dedicated thread that owns
/// a current-thread tokio runtime. Mirrors `status::run_status_loop`.
pub fn run_fleet_loops(monitor: Arc<StatusMonitor>, shutdown: ShutdownHandler) {
    run_fleet_loops_supervised(monitor, shutdown, None);
}

/// Like [`run_fleet_loops`], but reports to a [`HeartbeatEngine`] — for consumers
/// that supervise every long-running thread with a watchdog.
pub fn run_fleet_loops_supervised(
    monitor: Arc<StatusMonitor>,
    shutdown: ShutdownHandler,
    watchdog: Option<(Arc<HeartbeatEngine>, String)>,
) {
    std::thread::Builder::new()
        .name("fleet-monitor".to_string())
        .spawn(move || {
            let rt = match tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
            {
                Ok(rt) => rt,
                Err(e) => {
                    log::error!("Failed to build fleet runtime: {}", e);
                    // Der Thread endet hier — ohne Abmeldung meldete der Watchdog
                    // gleich einen ausgefallenen Schläger, obwohl nie einer lief.
                    if let Some((engine, id)) = &watchdog {
                        engine.cancel(id);
                    }
                    return;
                }
            };
            rt.block_on(monitor.run_supervised(shutdown, watchdog));
        })
        .expect("spawn fleet-monitor thread");
}

impl StatusSource for StatusMonitor {
    fn get_status(&self) -> Value {
        let mut result = serde_json::Map::new();
        result.insert(
            "Connected".to_string(),
            Value::Bool(self.client.is_connected()),
        );
        result.insert(
            "Server".to_string(),
            Value::String(self.server_display.read().unwrap().clone()),
        );
        if let Some(ref ts) = self.client.last_send_attempt() {
            result.insert("Last send attempt".to_string(), Value::String(ts.clone()));
        }
        if let Some(ref ts) = self.client.last_send_success() {
            result.insert("Last send success".to_string(), Value::String(ts.clone()));
        }
        if !self.client.is_connected() {
            if let Some(ref err) = self.client.last_connect_error() {
                result.insert("Error".to_string(), Value::String(err.clone()));
            }
        }
        Value::Object(result)
    }

    fn get_name(&self) -> &str {
        "FleetManager"
    }

    fn refresh_interval(&self) -> Duration {
        Duration::from_secs(60)
    }
}

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

    #[test]
    fn test_config_loading() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        std::fs::write(
            &path,
            r#"{"fleetmanagement": {"base_url": "https://fleet.test.com", "customer_name": "Acme", "machine": "Line-1", "token": "tok123"}}"#,
        )
        .unwrap();
        let cfg = FleetConfig::from_file(path.to_str().unwrap()).unwrap();
        assert_eq!(cfg.base_url.unwrap(), "https://fleet.test.com");
        assert_eq!(cfg.customer_name.unwrap(), "Acme");
        assert_eq!(cfg.machine.unwrap(), "Line-1");
        assert_eq!(cfg.token.unwrap(), "tok123");
    }

    #[test]
    fn test_config_legacy_broker() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        std::fs::write(
            &path,
            r#"{"fleetmanagement": {"broker": "fleet.brinkhaus-gmbh.de", "customer_name": "Test"}}"#,
        )
        .unwrap();
        let cfg = FleetConfig::from_file(path.to_str().unwrap()).unwrap();
        assert!(cfg.base_url.is_none());
        assert_eq!(cfg.resolve_base_url(), "https://fleet.brinkhaus-gmbh.de");
    }

    #[test]
    fn test_env_var_overrides() {
        let cfg = FleetConfig {
            customer_name: Some("config-customer".to_string()),
            machine: Some("config-machine".to_string()),
            ..Default::default()
        };
        std::env::set_var("STATUS_MONITOR_CUSTOMERID", "env-customer");
        assert_eq!(cfg.resolve_customer(), "env-customer");
        std::env::remove_var("STATUS_MONITOR_CUSTOMERID");
        assert_eq!(cfg.resolve_customer(), "config-customer");
    }

    #[test]
    fn test_config_parses_location() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        std::fs::write(
            &path,
            r#"{"fleetmanagement": {"base_url": "https://x", "location": "Halle 1"}}"#,
        )
        .unwrap();
        let cfg = FleetConfig::from_file(path.to_str().unwrap()).unwrap();
        assert_eq!(cfg.location.as_deref(), Some("Halle 1"));

        // Missing location key => None (field not sent).
        std::fs::write(&path, r#"{"fleetmanagement": {"base_url": "https://x"}}"#).unwrap();
        let cfg2 = FleetConfig::from_file(path.to_str().unwrap()).unwrap();
        assert_eq!(cfg2.location, None);
    }

    #[test]
    fn test_config_parses_device_identity() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        std::fs::write(
            &path,
            r#"{"fleetmanagement": {"base_url": "https://x", "serial": " SN00100 ",
                "display_name": "Drehmaschine 1", "inventory_no": "INV-1", "stream": "brinkhaus",
                "initial_password_scheme": "hmac-sn-v1", "initial_password_changed": true}}"#,
        )
        .unwrap();
        let cfg = FleetConfig::from_file(path.to_str().unwrap()).unwrap();
        assert_eq!(
            cfg.identity,
            DeviceIdentity {
                serial: Some("SN00100".to_string()),
                display_name: Some("Drehmaschine 1".to_string()),
                inventory_no: Some("INV-1".to_string()),
                stream: Some("brinkhaus".to_string()),
                branding: None,
                initial_password_scheme: Some("hmac-sn-v1".to_string()),
                initial_password_changed: Some(true),
            }
        );

        // Missing keys => nothing is sent.
        std::fs::write(&path, r#"{"fleetmanagement": {"base_url": "https://x"}}"#).unwrap();
        let cfg2 = FleetConfig::from_file(path.to_str().unwrap()).unwrap();
        assert_eq!(cfg2.identity, DeviceIdentity::default());
    }

    #[test]
    fn test_serial_file_takes_precedence_and_unreadable_file_sends_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let serial_file = dir.path().join("serial");
        std::fs::write(&serial_file, "SN00200\n").unwrap();
        let fm = serde_json::json!({
            "serial_file": serial_file.to_str().unwrap(),
            "serial": "SN00100",
        });
        assert_eq!(DeviceIdentity::from_fleet_json(&fm).serial.as_deref(), Some("SN00200"));

        let fm_missing = serde_json::json!({
            "serial_file": dir.path().join("missing").to_str().unwrap(),
            "serial": "SN00100",
        });
        assert_eq!(DeviceIdentity::from_fleet_json(&fm_missing).serial, None);
    }

    #[test]
    fn test_env_token_precedence() {
        let cfg = FleetConfig {
            token: Some("config-token".to_string()),
            ..Default::default()
        };
        std::env::set_var("FLEET_TOKEN", "env-token");
        assert_eq!(cfg.resolve_token(), Some("env-token".to_string()));
        std::env::remove_var("FLEET_TOKEN");
        assert_eq!(cfg.resolve_token(), Some("config-token".to_string()));
        // No env and no config token → None.
        let empty = FleetConfig::default();
        assert_eq!(empty.resolve_token(), None);
    }

    #[test]
    fn test_diagnosis_mapping() {
        // Create a valid config file so no 7001 diagnosis is added
        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.json");
        std::fs::write(
            &config_path,
            r#"{"fleetmanagement": {"base_url": "https://test.com", "customer_name": "t", "machine": "t"}}"#,
        ).unwrap();

        let diag = Arc::new(SelfDiagnosisEngine::new());
        diag.notify(100, "Test warning", Severity::Warning);
        diag.notify(200, "Test error", Severity::Error);
        diag.notify(300, "Test info", Severity::Info);

        let monitor = StatusMonitor::new(
            Some(config_path.to_str().unwrap()),
            Some(diag),
            "test",
            None,
            None,
            None,
            None,
            None,
            None,
        );

        let mapped = monitor.map_diagnosis();
        assert_eq!(mapped.len(), 3);

        let warning = mapped.iter().find(|m| m.0 == 100).unwrap();
        assert_eq!(warning.2, 1); // Warning = 1

        let error = mapped.iter().find(|m| m.0 == 200).unwrap();
        assert_eq!(error.2, 2); // Error = 2

        let info = mapped.iter().find(|m| m.0 == 300).unwrap();
        assert_eq!(info.2, 0); // Info = 0
    }

    #[test]
    fn test_missing_config_diagnosis_7001() {
        let diag = Arc::new(SelfDiagnosisEngine::new());
        let _monitor = StatusMonitor::new(
            Some("/nonexistent/config.json"),
            Some(diag.clone()),
            "test",
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let msgs = diag.get_messages();
        let m = msgs.iter().find(|m| m.code == 7001).expect("7001");
        assert_eq!(m.parts[0].key, "diag.detail.7001.configMissing");
        assert_eq!(
            m.parts[0].params["path"],
            DiagParam::Text("/nonexistent/config.json".into())
        );
    }

    #[test]
    fn test_status_source_impl() {
        let monitor = StatusMonitor::new(
            None,
            None,
            "test",
            None,
            None,
            None,
            None,
            None,
            None,
        );
        assert_eq!(monitor.get_name(), "FleetManager");
        let status = monitor.get_status();
        assert!(status.get("Connected").is_some());
    }

    /// Behavioral conformance: starting the monitor MUST drive heartbeat,
    /// diagnostics AND status POSTs to the ingest server. Regression guard for
    /// the "start() sends nothing" bug (brinkhaus/brinkhaustools#5).
    #[tokio::test]
    async fn conformance_run_sends_heartbeat_diagnostics_status() {
        let mock_server = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})),
            )
            .mount(&mock_server)
            .await;

        let dir = tempfile::tempdir().unwrap();
        let config_path = dir.path().join("config.json");
        std::fs::write(
            &config_path,
            format!(
                r#"{{"fleetmanagement": {{"base_url": "{}", "customer_name": "c", "machine": "m", "heartbeat_interval_sec": 1, "serial": "SN00100", "display_name": "Drehmaschine 1", "inventory_no": "INV-4711", "stream": "brinkhaus", "initial_password_scheme": "hmac-sn-v1", "initial_password_changed": false}}}}"#,
                mock_server.uri()
            ),
        )
        .unwrap();

        let monitor = Arc::new(StatusMonitor::new(
            Some(config_path.to_str().unwrap()),
            None,
            "conformance",
            Some("1.0.0"),
            None,
            None,
            None,
            None,
            None,
        ));
        monitor.set_branding(Some("uttec".to_string()));
        monitor.set_licence(Some(serde_json::json!({
            "installation_id": "3f0c7a52-0f7e-4b39-9a43-5d7a8c9b1e20",
            "state": "trial",
            "licences": [],
            "hardware": [{"type": "mac", "label": "eth0", "sha256": "ab".repeat(32)}],
            "trial": {"started_at": "2026-11-05T10:00:00Z", "expires_at": "2026-11-19T10:00:00Z"}
        })));
        monitor.set_hardware(Some(serde_json::json!({
            "model": "LEX 2I640DW",
            "disk_total_mb": 54082
        })));
        monitor.register_command(
            CommandSpec::new(
                "install-licence",
                BTreeMap::from([("en".to_string(), "Install licence".to_string())]),
                |_| ("success".to_string(), String::new()),
            )
            .system(),
        );
        monitor.set_controller_timing_for_testing(
            Duration::from_millis(200),
            Duration::from_millis(300),
        );

        let shutdown = ShutdownHandler::new();
        let handle = {
            let m = monitor.clone();
            let sd = shutdown.clone();
            tokio::spawn(async move { m.run(sd).await })
        };

        // Let the loops run, then stop and wait for the final status to flush.
        tokio::time::sleep(Duration::from_millis(2500)).await;
        shutdown.trigger();
        let _ = handle.await;

        let requests = mock_server.received_requests().await.unwrap();
        let count = |needle: &str| {
            requests
                .iter()
                .filter(|r| r.url.path().ends_with(needle))
                .count()
        };
        assert!(count("/heartbeat") >= 1, "no heartbeat POSTs received");
        assert!(count("/diagnostics") >= 1, "no diagnostics POSTs received");
        assert!(count("/status") >= 1, "no status POSTs received");

        // Device identity rides along on the heartbeat.
        let identity_sent = requests
            .iter()
            .filter(|r| r.url.path().ends_with("/heartbeat"))
            .filter_map(|r| serde_json::from_slice::<Value>(&r.body).ok())
            .any(|b| {
                b["serial"] == "SN00100"
                    && b["branding"] == "uttec"
                    && b["initial_password_changed"] == false
            });
        assert!(identity_sent, "device identity missing from heartbeat");

        // Licence report rides on the heartbeat, the command catalog on the snapshot.
        assert!(requests
            .iter()
            .filter(|r| r.url.path().ends_with("/heartbeat"))
            .filter_map(|r| serde_json::from_slice::<Value>(&r.body).ok())
            .any(|b| b["licence"]["state"] == "trial"));
        assert!(requests
            .iter()
            .filter(|r| r.url.path().ends_with("/heartbeat"))
            .filter_map(|r| serde_json::from_slice::<Value>(&r.body).ok())
            .any(|b| b["hardware"]["disk_total_mb"] == 54082));
        assert!(requests
            .iter()
            .filter(|r| r.url.path().ends_with("/status"))
            .filter_map(|r| serde_json::from_slice::<Value>(&r.body).ok())
            .any(|b| b["snapshot"]["commands"][0]["id"] == "install-licence"
                && b["snapshot"]["commands"][0]["system"] == true));

        // Every emitted payload must conform to the shared JSON schemas
        // (test-fixtures/schemas) — the cross-language wire contract.
        let schema_dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../test-fixtures/schemas/");
        let load = |name: &str| -> Value {
            serde_json::from_str(
                &std::fs::read_to_string(format!("{}{}", schema_dir, name)).unwrap(),
            )
            .unwrap()
        };
        let hb = load("heartbeat.schema.json");
        let diag = load("diagnostics.schema.json");
        let status = load("status.schema.json");
        for req in &requests {
            let body: Value = serde_json::from_slice(&req.body).unwrap();
            let path = req.url.path();
            let schema = if path.ends_with("/heartbeat") {
                &hb
            } else if path.ends_with("/diagnostics") {
                &diag
            } else {
                &status
            };
            validate_schema_lite(&body, schema)
                .unwrap_or_else(|e| panic!("payload for {} violates schema: {}", path, e));
        }

        // Lifecycle: initial `running` and final `stopped` status must be sent.
        let status_values: Vec<String> = requests
            .iter()
            .filter(|r| r.url.path().ends_with("/status"))
            .filter_map(|r| serde_json::from_slice::<Value>(&r.body).ok())
            .filter_map(|b| b.get("status").and_then(|s| s.as_str()).map(String::from))
            .collect();
        assert!(
            status_values.iter().any(|s| s == "running"),
            "no initial 'running' status; saw {:?}",
            status_values
        );
        assert!(
            status_values.iter().any(|s| s == "stopped"),
            "no final 'stopped' status; saw {:?}",
            status_values
        );
    }

    #[tokio::test]
    async fn diag_7002_set_on_failure_and_clear_on_success() {
        // Failure: point at a closed port; the controller must raise 7002.
        let diag = Arc::new(SelfDiagnosisEngine::new());
        let dir = tempfile::tempdir().unwrap();
        let cfg = dir.path().join("c.json");
        std::fs::write(
            &cfg,
            r#"{"fleetmanagement": {"base_url": "http://127.0.0.1:1", "customer_name": "c", "machine": "m", "heartbeat_interval_sec": 1}}"#,
        )
        .unwrap();
        let monitor = Arc::new(StatusMonitor::new(
            Some(cfg.to_str().unwrap()),
            Some(diag.clone()),
            "t",
            None,
            None,
            None,
            None,
            None,
            None,
        ));
        monitor.set_controller_timing_for_testing(
            Duration::from_millis(100),
            Duration::from_millis(200),
        );
        let sd = ShutdownHandler::new();
        run_fleet_loops(monitor.clone(), sd.clone());
        let mut had_7002 = false;
        for _ in 0..40 {
            if diag.get_messages().iter().any(|m| m.code == 7002) {
                had_7002 = true;
                break;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
        sd.trigger();
        assert!(had_7002, "7002 not set on connection failure");
        // Edges run unattended and are often offline by design — connectivity
        // failure must be informational, never critical.
        let msg = diag
            .get_messages()
            .into_iter()
            .find(|m| m.code == 7002)
            .expect("7002 message present");
        assert_eq!(msg.severity, Severity::Info, "7002 must not be critical");

        // Success: a reachable mock clears 7002.
        let mock = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
            .mount(&mock)
            .await;
        let diag2 = Arc::new(SelfDiagnosisEngine::new());
        let cfg2 = dir.path().join("c2.json");
        std::fs::write(
            &cfg2,
            format!(
                r#"{{"fleetmanagement": {{"base_url": "{}", "customer_name": "c", "machine": "m", "heartbeat_interval_sec": 1}}}}"#,
                mock.uri()
            ),
        )
        .unwrap();
        let monitor2 = Arc::new(StatusMonitor::new(
            Some(cfg2.to_str().unwrap()),
            Some(diag2.clone()),
            "t",
            None,
            None,
            None,
            None,
            None,
            None,
        ));
        monitor2.set_controller_timing_for_testing(
            Duration::from_millis(100),
            Duration::from_millis(200),
        );
        let sd2 = ShutdownHandler::new();
        run_fleet_loops(monitor2.clone(), sd2.clone());
        tokio::time::sleep(Duration::from_millis(1500)).await;
        sd2.trigger();
        assert!(
            !diag2.get_messages().iter().any(|m| m.code == 7002),
            "7002 should be cleared once connected"
        );
    }

    #[tokio::test]
    async fn commands_are_dispatched_and_acknowledged() {
        let mock = wiremock::MockServer::start().await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path_regex(".*/heartbeat$"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "commands": [
                    {"id": 7, "command_id": "install-licence", "payload": {"licence": "BLIC1-X"}},
                    {"id": 8, "command_id": "nope"},
                    {"command_id": "install-licence"}
                ]
            })))
            .up_to_n_times(1)
            .mount(&mock)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({})))
            .mount(&mock)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let cfg = dir.path().join("c.json");
        std::fs::write(
            &cfg,
            format!(
                r#"{{"fleetmanagement": {{"base_url": "{}", "customer_name": "c", "machine": "m", "heartbeat_interval_sec": 60}}}}"#,
                mock.uri()
            ),
        )
        .unwrap();
        let monitor = Arc::new(StatusMonitor::new(
            Some(cfg.to_str().unwrap()), None, "t", None, None, None, None, None, None,
        ));
        let seen = Arc::new(Mutex::new(None));
        let seen_in = Arc::clone(&seen);
        monitor.register_command(CommandSpec::new(
            "install-licence",
            BTreeMap::from([("en".to_string(), "Install licence".to_string())]),
            move |payload| {
                *seen_in.lock().unwrap() = payload;
                ("success".to_string(), "installed".to_string())
            },
        ));
        monitor.set_controller_timing_for_testing(Duration::from_secs(60), Duration::from_secs(60));
        let sd = ShutdownHandler::new();
        let handle = {
            let (m, sd) = (monitor.clone(), sd.clone());
            tokio::spawn(async move { m.run(sd).await })
        };
        let mut acks: Vec<Value> = Vec::new();
        for _ in 0..40 {
            tokio::time::sleep(Duration::from_millis(100)).await;
            acks = mock
                .received_requests()
                .await
                .unwrap()
                .iter()
                .filter(|r| r.url.path().ends_with("/command-ack"))
                .filter_map(|r| serde_json::from_slice::<Value>(&r.body).ok())
                .flat_map(|b| b["acks"].as_array().cloned().unwrap_or_default())
                .collect();
            if acks.len() >= 2 {
                break;
            }
        }
        sd.trigger();
        let _ = handle.await;
        let by_id = |id: i64| acks.iter().find(|a| a["id"] == id).cloned();
        assert_eq!(by_id(7).expect("ack for 7")["result"], "success");
        assert_eq!(by_id(8).expect("ack for 8")["result"], "rejected");
        assert_eq!(acks.len(), 2, "malformed command must not be acknowledged: {acks:?}");
        assert_eq!(seen.lock().unwrap().clone().unwrap()["licence"], "BLIC1-X");
    }

    /// Dependency-free schema check: every `required` field present, and (when
    /// `additionalProperties` is false) no unknown top-level field. Enough to
    /// catch cross-language field/shape drift.
    fn validate_schema_lite(instance: &Value, schema: &Value) -> Result<(), String> {
        if let Some(req) = schema.get("required").and_then(|r| r.as_array()) {
            for r in req {
                let k = r.as_str().unwrap_or("");
                if instance.get(k).is_none() {
                    return Err(format!("missing required field '{}'", k));
                }
            }
        }
        let additional = schema
            .get("additionalProperties")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        if !additional {
            if let (Some(obj), Some(props)) = (
                instance.as_object(),
                schema.get("properties").and_then(|p| p.as_object()),
            ) {
                for k in obj.keys() {
                    if !props.contains_key(k) {
                        return Err(format!("unexpected field '{}'", k));
                    }
                }
            }
        }
        Ok(())
    }
}