wasma-sys 1.3.0-beta-stable

WASMA Windows Assignment System Monitoring Architecture — client and protocol layer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
// WASMA - Windows Assignment System Monitoring Architecture
// wasma_client_unix_posix_raw_applettel.rs
// Raw POSIX Applet Letting Client
// Applets access application data structures directly via letting protocol.
// Reactive mode: continuously listens, triggers on change.
// Supports both system applets (tray, panel, widget) and embedded applets.
// Independent from UClientEngine — pure letting protocol only.
// January 2026

use std::collections::HashMap;
use std::os::unix::io::RawFd;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};

use crate::parser::WasmaConfig;
use crate::wasma_client_unix_posix_raw_app::posix;

// ============================================================================
// LETTING PROTOCOL
// ============================================================================
// Applet ↔ Host application communication over POSIX fd.
// Fixed 20-byte header + variable payload.
//
// Header layout:
//   [0..4]   magic:      0x4C 0x45 0x54 0x4C  ("LETL")
//   [4..8]   msg_type:   LettingMsgType (u32 LE)
//   [8..12]  applet_id:  u32 LE
//   [12..16] seq:        u32 LE  (sequence number, wraps at u32::MAX)
//   [16..20] payload_len:u32 LE
//
// Response header:
//   [0..4]   magic:      0x4C 0x52 0x53 0x50  ("LRSP")
//   [4..8]   status:     LettingStatus (u32 LE)
//   [8..12]  applet_id:  u32 LE
//   [12..16] seq:        u32 LE  (mirrors request seq)
//   [16..20] payload_len:u32 LE

pub const LETTING_CMD_MAGIC: [u8; 4] = [0x4C, 0x45, 0x54, 0x4C]; // "LETL"
pub const LETTING_RSP_MAGIC: [u8; 4] = [0x4C, 0x52, 0x53, 0x50]; // "LRSP"
pub const LETTING_HDR_SIZE: usize = 20;

/// Letting protocol message types
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LettingMsgType {
    /// Register applet with host
    Register = 0x01,
    /// Unregister applet
    Unregister = 0x02,
    /// Subscribe to a data field
    Subscribe = 0x03,
    /// Unsubscribe from a data field
    Unsubscribe = 0x04,
    /// Request current value of a field
    GetField = 0x05,
    /// Host pushes field change notification
    FieldChanged = 0x06,
    /// Applet sends data to host
    PushData = 0x07,
    /// Request full data snapshot
    Snapshot = 0x08,
    /// Keepalive ping
    Ping = 0xFE,
    /// Disconnect gracefully
    Disconnect = 0xFF,
}

impl LettingMsgType {
    pub fn from_u32(v: u32) -> Option<Self> {
        match v {
            0x01 => Some(Self::Register),
            0x02 => Some(Self::Unregister),
            0x03 => Some(Self::Subscribe),
            0x04 => Some(Self::Unsubscribe),
            0x05 => Some(Self::GetField),
            0x06 => Some(Self::FieldChanged),
            0x07 => Some(Self::PushData),
            0x08 => Some(Self::Snapshot),
            0xFE => Some(Self::Ping),
            0xFF => Some(Self::Disconnect),
            _ => None,
        }
    }

    pub fn to_u32(self) -> u32 {
        self as u32
    }
}

/// Letting protocol status codes
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LettingStatus {
    Ok = 0x00,
    Accepted = 0x01,
    ErrNotFound = 0x10,
    ErrPermission = 0x11,
    ErrInvalidField = 0x12,
    ErrInternal = 0x13,
    ErrAlreadyReg = 0x14,
    Pong = 0xFE,
    Disconnected = 0xFF,
}

impl LettingStatus {
    pub fn from_u32(v: u32) -> Self {
        match v {
            0x00 => Self::Ok,
            0x01 => Self::Accepted,
            0x10 => Self::ErrNotFound,
            0x11 => Self::ErrPermission,
            0x12 => Self::ErrInvalidField,
            0x13 => Self::ErrInternal,
            0x14 => Self::ErrAlreadyReg,
            0xFE => Self::Pong,
            0xFF => Self::Disconnected,
            _ => Self::ErrInternal,
        }
    }
}

// ============================================================================
// APPLET KIND
// ============================================================================

/// Applet type — system-level or embedded inside an application
#[derive(Debug, Clone, PartialEq)]
pub enum AppletKind {
    /// System applet: tray icon, panel widget, status bar element
    System(SystemAppletRole),
    /// Embedded applet: lives inside a host application window
    Embedded(EmbeddedAppletRole),
}

/// System applet roles
#[derive(Debug, Clone, PartialEq)]
pub enum SystemAppletRole {
    TrayIcon,
    PanelWidget,
    StatusBarItem,
    NotificationArea,
    QuickSettings,
    Custom(String),
}

/// Embedded applet roles
#[derive(Debug, Clone, PartialEq)]
pub enum EmbeddedAppletRole {
    /// Mini view embedded in parent window
    MiniView,
    /// Sidebar panel inside application
    SidePanel,
    /// Toolbar extension
    ToolbarExtension,
    /// Floating overlay
    FloatingOverlay,
    /// Data inspector / debug panel
    Inspector,
    Custom(String),
}

impl AppletKind {
    pub fn display_name(&self) -> String {
        match self {
            Self::System(role) => format!("system::{:?}", role),
            Self::Embedded(role) => format!("embedded::{:?}", role),
        }
    }

    pub fn is_system(&self) -> bool {
        matches!(self, Self::System(_))
    }

    pub fn is_embedded(&self) -> bool {
        matches!(self, Self::Embedded(_))
    }
}

// ============================================================================
// LETTING EVENTS — Reactive trigger system
// ============================================================================

/// A field that an applet can subscribe to
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FieldKey {
    /// Namespace: e.g. "window", "resource", "user", "app"
    pub namespace: String,
    /// Field name: e.g. "title", "geometry", "state", "cpu_usage"
    pub name: String,
}

impl FieldKey {
    pub fn new(namespace: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            namespace: namespace.into(),
            name: name.into(),
        }
    }

    pub fn encode(&self) -> Vec<u8> {
        let ns = self.namespace.as_bytes();
        let nm = self.name.as_bytes();
        let mut buf = Vec::with_capacity(2 + ns.len() + 2 + nm.len());
        buf.extend_from_slice(&(ns.len() as u16).to_le_bytes());
        buf.extend_from_slice(ns);
        buf.extend_from_slice(&(nm.len() as u16).to_le_bytes());
        buf.extend_from_slice(nm);
        buf
    }

    pub fn decode(buf: &[u8]) -> Option<(Self, usize)> {
        if buf.len() < 2 {
            return None;
        }
        let ns_len = u16::from_le_bytes(buf[0..2].try_into().ok()?) as usize;
        if buf.len() < 2 + ns_len + 2 {
            return None;
        }
        let namespace = String::from_utf8(buf[2..2 + ns_len].to_vec()).ok()?;
        let nm_len = u16::from_le_bytes(buf[2 + ns_len..4 + ns_len].try_into().ok()?) as usize;
        if buf.len() < 4 + ns_len + nm_len {
            return None;
        }
        let name = String::from_utf8(buf[4 + ns_len..4 + ns_len + nm_len].to_vec()).ok()?;
        let consumed = 4 + ns_len + nm_len;
        Some((Self { namespace, name }, consumed))
    }
}

/// Field value — raw bytes with optional type hint
#[derive(Debug, Clone)]
pub struct FieldValue {
    pub raw: Vec<u8>,
    pub type_hint: FieldTypeHint,
    pub updated_at: SystemTime,
}

impl FieldValue {
    pub fn new(raw: Vec<u8>, type_hint: FieldTypeHint) -> Self {
        Self {
            raw,
            type_hint,
            updated_at: SystemTime::now(),
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        std::str::from_utf8(&self.raw).ok()
    }

    pub fn as_u64(&self) -> Option<u64> {
        self.raw
            .get(0..8)
            .and_then(|b| b.try_into().ok())
            .map(u64::from_le_bytes)
    }

    pub fn as_f64(&self) -> Option<f64> {
        self.raw
            .get(0..8)
            .and_then(|b| b.try_into().ok())
            .map(f64::from_le_bytes)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum FieldTypeHint {
    Bytes,
    String,
    U64,
    F64,
    Bool,
    Json,
}

/// A reactive letting event delivered to the applet
#[derive(Debug, Clone)]
pub struct LettingEvent {
    /// Which field changed
    pub field: FieldKey,
    /// New value
    pub value: FieldValue,
    /// Previous value if available
    pub previous: Option<FieldValue>,
    /// Sequence number from host
    pub seq: u32,
    /// When the event was received
    pub received_at: SystemTime,
}

/// Event handler function type
pub type LettingHandler = Arc<dyn Fn(&LettingEvent) + Send + Sync>;

// ============================================================================
// LETTING FD — POSIX fd channel for letting protocol
// ============================================================================

pub struct LettingFd {
    fd: Option<RawFd>,
    seq: u32,
    connected: bool,
}

impl LettingFd {
    pub fn new() -> Self {
        Self {
            fd: None,
            seq: 0,
            connected: false,
        }
    }

    pub fn connect_unix(&mut self, path: &str) -> Result<(), std::io::Error> {
        use std::os::unix::io::AsRawFd;
        use std::os::unix::net::UnixStream;
        let stream = UnixStream::connect(path)?;
        let fd = stream.as_raw_fd();
        let _ = std::mem::ManuallyDrop::new(stream);
        self.fd = Some(fd);
        self.connected = true;
        Ok(())
    }

    pub fn connect_tcp(&mut self, ip: &str, port: u16) -> Result<(), std::io::Error> {
        use std::net::TcpStream;
        use std::os::unix::io::AsRawFd;
        let stream = TcpStream::connect(format!("{}:{}", ip, port))?;
        let fd = stream.as_raw_fd();
        let _ = std::mem::ManuallyDrop::new(stream);
        self.fd = Some(fd);
        self.connected = true;
        Ok(())
    }

    fn next_seq(&mut self) -> u32 {
        let s = self.seq;
        self.seq = self.seq.wrapping_add(1);
        s
    }

    /// Send a letting message, return (status, seq, payload)
    pub fn send(
        &mut self,
        msg_type: LettingMsgType,
        applet_id: u32,
        payload: &[u8],
    ) -> Result<(LettingStatus, u32, Vec<u8>), std::io::Error> {
        let fd = self.fd.ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::NotConnected, "Letting channel not open")
        })?;

        let seq = self.next_seq();

        // Build header
        let mut hdr = [0u8; LETTING_HDR_SIZE];
        hdr[0..4].copy_from_slice(&LETTING_CMD_MAGIC);
        hdr[4..8].copy_from_slice(&msg_type.to_u32().to_le_bytes());
        hdr[8..12].copy_from_slice(&applet_id.to_le_bytes());
        hdr[12..16].copy_from_slice(&seq.to_le_bytes());
        hdr[16..20].copy_from_slice(&(payload.len() as u32).to_le_bytes());

        // Write header + payload
        self.write_all(fd, &hdr)?;
        if !payload.is_empty() {
            self.write_all(fd, payload)?;
        }

        // Read response
        let mut rsp_hdr = [0u8; LETTING_HDR_SIZE];
        posix::posix_read_exact(fd, &mut rsp_hdr)?;

        if rsp_hdr[0..4] != LETTING_RSP_MAGIC {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("Invalid response magic: {:?}", &rsp_hdr[0..4]),
            ));
        }

        let status = LettingStatus::from_u32(u32::from_le_bytes(rsp_hdr[4..8].try_into().unwrap()));
        let resp_seq = u32::from_le_bytes(rsp_hdr[12..16].try_into().unwrap());
        let payload_len = u32::from_le_bytes(rsp_hdr[16..20].try_into().unwrap()) as usize;

        let mut resp_payload = vec![0u8; payload_len];
        if payload_len > 0 {
            posix::posix_read_exact(fd, &mut resp_payload)?;
        }

        Ok((status, resp_seq, resp_payload))
    }

    /// Poll for an incoming event from host (non-blocking, timeout_ms)
    /// Returns raw header + payload if available
    pub fn poll_event(
        &self,
        timeout_ms: i32,
    ) -> Result<Option<(LettingMsgType, u32, Vec<u8>)>, std::io::Error> {
        let fd = self.fd.ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::NotConnected, "Letting channel not open")
        })?;

        match posix::posix_poll_readable(fd, timeout_ms)? {
            false => return Ok(None),
            true => {}
        }

        let mut hdr = [0u8; LETTING_HDR_SIZE];
        posix::posix_read_exact(fd, &mut hdr)?;

        if hdr[0..4] != LETTING_CMD_MAGIC {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Invalid event magic",
            ));
        }

        let msg_type = LettingMsgType::from_u32(u32::from_le_bytes(hdr[4..8].try_into().unwrap()))
            .ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::InvalidData, "Unknown message type")
            })?;

        let seq = u32::from_le_bytes(hdr[12..16].try_into().unwrap());
        let payload_len = u32::from_le_bytes(hdr[16..20].try_into().unwrap()) as usize;

        let mut payload = vec![0u8; payload_len];
        if payload_len > 0 {
            posix::posix_read_exact(fd, &mut payload)?;
        }

        Ok(Some((msg_type, seq, payload)))
    }

    fn write_all(&self, fd: RawFd, buf: &[u8]) -> Result<(), std::io::Error> {
        let mut written = 0;
        while written < buf.len() {
            let n = unsafe {
                libc::write(
                    fd,
                    buf[written..].as_ptr() as *const libc::c_void,
                    buf.len() - written,
                )
            };
            match n {
                -1 => return Err(std::io::Error::last_os_error()),
                0 => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::WriteZero,
                        "write() returned zero",
                    ))
                }
                n => written += n as usize,
            }
        }
        Ok(())
    }

    pub fn fd(&self) -> Option<RawFd> {
        self.fd
    }
    pub fn is_connected(&self) -> bool {
        self.connected
    }
}

impl Drop for LettingFd {
    fn drop(&mut self) {
        if let Some(fd) = self.fd.take() {
            if fd != 0 {
                let _ = posix::posix_close(fd);
            }
        }
    }
}

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

// ============================================================================
// APPLET DESCRIPTOR — Applet identity and metadata
// ============================================================================

#[derive(Debug, Clone)]
pub struct AppletDescriptor {
    /// Unique applet ID (assigned by host on Register)
    pub id: u32,
    /// Human-readable applet name
    pub name: String,
    /// Version string
    pub version: String,
    /// Applet kind
    pub kind: AppletKind,
    /// Host app ID this applet is attached to
    pub host_app_id: String,
    /// Host window ID (for embedded applets)
    pub host_window_id: Option<u64>,
    /// Registration time
    pub registered_at: SystemTime,
}

impl AppletDescriptor {
    pub fn new(
        name: impl Into<String>,
        version: impl Into<String>,
        kind: AppletKind,
        host_app_id: impl Into<String>,
    ) -> Self {
        Self {
            id: 0, // assigned by host
            name: name.into(),
            version: version.into(),
            kind,
            host_app_id: host_app_id.into(),
            host_window_id: None,
            registered_at: SystemTime::now(),
        }
    }

    /// Encode descriptor for Register payload
    pub fn encode(&self) -> Vec<u8> {
        let name = self.name.as_bytes();
        let ver = self.version.as_bytes();
        let host = self.host_app_id.as_bytes();
        let kind_byte: u8 = if self.kind.is_system() { 0x01 } else { 0x02 };
        let win_id = self.host_window_id.unwrap_or(0u64);

        let mut buf = Vec::new();
        buf.extend_from_slice(&(name.len() as u16).to_le_bytes());
        buf.extend_from_slice(name);
        buf.extend_from_slice(&(ver.len() as u16).to_le_bytes());
        buf.extend_from_slice(ver);
        buf.extend_from_slice(&(host.len() as u16).to_le_bytes());
        buf.extend_from_slice(host);
        buf.push(kind_byte);
        buf.extend_from_slice(&win_id.to_le_bytes());
        buf
    }
}

// ============================================================================
// FIELD CACHE — Local cache of subscribed field values
// ============================================================================

pub struct FieldCache {
    fields: HashMap<FieldKey, FieldValue>,
}

impl FieldCache {
    pub fn new() -> Self {
        Self {
            fields: HashMap::new(),
        }
    }

    pub fn update(&mut self, key: FieldKey, value: FieldValue) -> Option<FieldValue> {
        self.fields.insert(key, value)
    }

    pub fn get(&self, key: &FieldKey) -> Option<&FieldValue> {
        self.fields.get(key)
    }

    pub fn remove(&mut self, key: &FieldKey) -> Option<FieldValue> {
        self.fields.remove(key)
    }

    pub fn keys(&self) -> impl Iterator<Item = &FieldKey> {
        self.fields.keys()
    }

    pub fn len(&self) -> usize {
        self.fields.len()
    }

    pub fn is_empty(&self) -> bool {
        self.fields.is_empty()
    }
}

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

// ============================================================================
// APPLETTEL CLIENT — Main struct, pure letting protocol
// ============================================================================

/// ApplettelClient
///
/// Applets continuously listen to host application data via the letting protocol.
/// Reactive: triggers registered handlers when subscribed fields change.
/// Fully independent from UClientEngine — letting protocol only.
///
/// Lifecycle:
///   1. connect()      → open POSIX fd to host letting socket
///   2. register()     → identify applet to host, receive applet_id
///   3. subscribe()    → subscribe to desired fields
///   4. run_loop()     → reactive event loop, triggers handlers on change
///   5. unregister()   → graceful disconnect
pub struct ApplettelClient {
    config: Arc<WasmaConfig>,

    /// Applet identity
    descriptor: AppletDescriptor,

    /// Letting POSIX fd channel
    fd: LettingFd,

    /// Local field value cache
    cache: Arc<Mutex<FieldCache>>,

    /// Reactive handlers: field key → handler fn
    handlers: Arc<Mutex<HashMap<FieldKey, Vec<LettingHandler>>>>,

    /// Subscribed field keys
    subscriptions: Arc<Mutex<Vec<FieldKey>>>,

    /// Running state
    running: Arc<Mutex<bool>>,

    /// Letting socket path
    socket_path: String,
}

impl ApplettelClient {
    pub fn new(config: WasmaConfig, descriptor: AppletDescriptor) -> Self {
        // Derive socket path from config protocols
        let socket_path = if let Some(proto) = config.uri_handling.protocols.first() {
            format!("/run/wasma/letting_{}.sock", proto.port)
        } else {
            "/run/wasma/letting.sock".to_string()
        };

        Self {
            descriptor,
            fd: LettingFd::new(),
            cache: Arc::new(Mutex::new(FieldCache::new())),
            handlers: Arc::new(Mutex::new(HashMap::new())),
            subscriptions: Arc::new(Mutex::new(Vec::new())),
            running: Arc::new(Mutex::new(false)),
            socket_path,
            config: Arc::new(config),
        }
    }

    pub fn from_config(config: Arc<WasmaConfig>, descriptor: AppletDescriptor) -> Self {
        let socket_path = if let Some(proto) = config.uri_handling.protocols.first() {
            format!("/run/wasma/letting_{}.sock", proto.port)
        } else {
            "/run/wasma/letting.sock".to_string()
        };

        Self {
            descriptor,
            fd: LettingFd::new(),
            cache: Arc::new(Mutex::new(FieldCache::new())),
            handlers: Arc::new(Mutex::new(HashMap::new())),
            subscriptions: Arc::new(Mutex::new(Vec::new())),
            running: Arc::new(Mutex::new(false)),
            socket_path,
            config,
        }
    }

    /// Override socket path
    pub fn with_socket(mut self, path: impl Into<String>) -> Self {
        self.socket_path = path.into();
        self
    }

    // -------------------------------------------------------------------------
    // CONNECTION
    // -------------------------------------------------------------------------

    /// Open POSIX fd connection to host letting socket
    pub fn connect(&mut self) -> Result<(), String> {
        self.fd
            .connect_unix(&self.socket_path)
            .map_err(|e| format!("Letting connect failed ({}): {}", self.socket_path, e))?;
        println!("🔌 ApplettelClient: Connected → {}", self.socket_path);
        Ok(())
    }

    /// Connect via TCP (for remote host apps)
    pub fn connect_tcp(&mut self, ip: &str, port: u16) -> Result<(), String> {
        self.fd
            .connect_tcp(ip, port)
            .map_err(|e| format!("Letting TCP connect failed ({}:{}): {}", ip, port, e))?;
        println!("🔌 ApplettelClient: Connected via TCP → {}:{}", ip, port);
        Ok(())
    }

    // -------------------------------------------------------------------------
    // REGISTRATION
    // -------------------------------------------------------------------------

    /// Register applet with host — receives assigned applet_id
    pub fn register(&mut self) -> Result<u32, String> {
        if !self.fd.is_connected() {
            return Err("Not connected — call connect() first".to_string());
        }

        let payload = self.descriptor.encode();
        match self.fd.send(LettingMsgType::Register, 0, &payload) {
            Ok((LettingStatus::Accepted, _, resp)) => {
                if resp.len() >= 4 {
                    let applet_id = u32::from_le_bytes(resp[0..4].try_into().unwrap());
                    self.descriptor.id = applet_id;
                    self.descriptor.registered_at = SystemTime::now();
                    println!(
                        "✅ ApplettelClient: Registered → id={} kind={}",
                        applet_id,
                        self.descriptor.kind.display_name()
                    );
                    Ok(applet_id)
                } else {
                    Err("Register: invalid response payload".to_string())
                }
            }
            Ok((LettingStatus::ErrAlreadyReg, _, _)) => {
                println!(
                    "⚠️  ApplettelClient: Already registered (id={})",
                    self.descriptor.id
                );
                Ok(self.descriptor.id)
            }
            Ok((status, _, _)) => Err(format!("Register failed: {:?}", status)),
            Err(e) => Err(format!("Register error: {}", e)),
        }
    }

    /// Unregister applet from host
    pub fn unregister(&mut self) -> Result<(), String> {
        if !self.fd.is_connected() {
            return Ok(());
        }

        let _ = self
            .fd
            .send(LettingMsgType::Unregister, self.descriptor.id, &[]);
        println!(
            "👋 ApplettelClient: Unregistered (id={})",
            self.descriptor.id
        );
        Ok(())
    }

    // -------------------------------------------------------------------------
    // SUBSCRIPTIONS
    // -------------------------------------------------------------------------

    /// Subscribe to a field — handler is called on every change
    pub fn subscribe(&mut self, field: FieldKey, handler: LettingHandler) -> Result<(), String> {
        // Send subscription to host
        if self.fd.is_connected() {
            let payload = field.encode();
            match self
                .fd
                .send(LettingMsgType::Subscribe, self.descriptor.id, &payload)
            {
                Ok((LettingStatus::Ok, _, _)) | Ok((LettingStatus::Accepted, _, _)) => {}
                Ok((status, _, _)) => {
                    return Err(format!("Subscribe failed for {:?}: {:?}", field, status));
                }
                Err(e) => {
                    eprintln!("⚠️  Subscribe send error: {} — registered locally only", e);
                }
            }
        }

        // Register handler locally
        let mut handlers = self.handlers.lock().unwrap();
        handlers.entry(field.clone()).or_default().push(handler);

        // Track subscription
        let mut subs = self.subscriptions.lock().unwrap();
        if !subs.contains(&field) {
            subs.push(field.clone());
        }

        println!(
            "📡 ApplettelClient: Subscribed → {}/{}",
            field.namespace, field.name
        );
        Ok(())
    }

    /// Unsubscribe from a field
    pub fn unsubscribe(&mut self, field: &FieldKey) -> Result<(), String> {
        if self.fd.is_connected() {
            let payload = field.encode();
            let _ = self
                .fd
                .send(LettingMsgType::Unsubscribe, self.descriptor.id, &payload);
        }

        let mut handlers = self.handlers.lock().unwrap();
        handlers.remove(field);

        let mut subs = self.subscriptions.lock().unwrap();
        subs.retain(|f| f != field);

        println!(
            "🔕 ApplettelClient: Unsubscribed → {}/{}",
            field.namespace, field.name
        );
        Ok(())
    }

    // -------------------------------------------------------------------------
    // FIELD ACCESS
    // -------------------------------------------------------------------------

    /// Get current value of a field (from cache first, then host)
    pub fn get_field(&mut self, field: &FieldKey) -> Result<FieldValue, String> {
        // Check local cache first
        {
            let cache = self.cache.lock().unwrap();
            if let Some(val) = cache.get(field) {
                return Ok(val.clone());
            }
        }

        // Ask host
        if self.fd.is_connected() {
            let payload = field.encode();
            match self
                .fd
                .send(LettingMsgType::GetField, self.descriptor.id, &payload)
            {
                Ok((LettingStatus::Ok, _, raw)) => {
                    let value = FieldValue::new(raw.clone(), FieldTypeHint::Bytes);
                    self.cache
                        .lock()
                        .unwrap()
                        .update(field.clone(), value.clone());
                    Ok(value)
                }
                Ok((status, _, _)) => Err(format!("GetField failed: {:?}", status)),
                Err(e) => Err(format!("GetField error: {}", e)),
            }
        } else {
            Err(format!(
                "Field {}/{} not in cache and not connected",
                field.namespace, field.name
            ))
        }
    }

    /// Push data to host application
    pub fn push_data(&mut self, field: &FieldKey, data: &[u8]) -> Result<(), String> {
        if !self.fd.is_connected() {
            return Err("Not connected".to_string());
        }

        let mut payload = field.encode();
        payload.extend_from_slice(&(data.len() as u32).to_le_bytes());
        payload.extend_from_slice(data);

        match self
            .fd
            .send(LettingMsgType::PushData, self.descriptor.id, &payload)
        {
            Ok((LettingStatus::Ok, _, _)) | Ok((LettingStatus::Accepted, _, _)) => Ok(()),
            Ok((status, _, _)) => Err(format!("PushData failed: {:?}", status)),
            Err(e) => Err(format!("PushData error: {}", e)),
        }
    }

    /// Request full data snapshot from host
    pub fn snapshot(&mut self) -> Result<HashMap<String, Vec<u8>>, String> {
        if !self.fd.is_connected() {
            return Err("Not connected".to_string());
        }

        match self
            .fd
            .send(LettingMsgType::Snapshot, self.descriptor.id, &[])
        {
            Ok((LettingStatus::Ok, _, payload)) => {
                // Decode: [count:u32][key_len:u16][key][val_len:u32][val]...
                let mut result = HashMap::new();
                let mut offset = 0;
                if payload.len() < 4 {
                    return Ok(result);
                }
                let count = u32::from_le_bytes(payload[0..4].try_into().unwrap()) as usize;
                offset += 4;
                for _ in 0..count {
                    if offset + 2 > payload.len() {
                        break;
                    }
                    let key_len =
                        u16::from_le_bytes(payload[offset..offset + 2].try_into().unwrap())
                            as usize;
                    offset += 2;
                    if offset + key_len + 4 > payload.len() {
                        break;
                    }
                    let key =
                        String::from_utf8_lossy(&payload[offset..offset + key_len]).to_string();
                    offset += key_len;
                    let val_len =
                        u32::from_le_bytes(payload[offset..offset + 4].try_into().unwrap())
                            as usize;
                    offset += 4;
                    if offset + val_len > payload.len() {
                        break;
                    }
                    let val = payload[offset..offset + val_len].to_vec();
                    offset += val_len;
                    result.insert(key, val);
                }
                println!(
                    "📸 ApplettelClient: Snapshot received — {} fields",
                    result.len()
                );
                Ok(result)
            }
            Ok((status, _, _)) => Err(format!("Snapshot failed: {:?}", status)),
            Err(e) => Err(format!("Snapshot error: {}", e)),
        }
    }

    // -------------------------------------------------------------------------
    // REACTIVE EVENT LOOP
    // -------------------------------------------------------------------------

    /// Main reactive loop — blocks until stop() is called.
    /// Polls for FieldChanged events, updates cache, triggers handlers.
    pub fn run_loop(&self) -> Result<(), Box<dyn std::error::Error>> {
        *self.running.lock().unwrap() = true;

        println!(
            "🔄 ApplettelClient: Reactive loop started (id={} kind={})",
            self.descriptor.id,
            self.descriptor.kind.display_name()
        );

        loop {
            if !*self.running.lock().unwrap() {
                println!("🛑 ApplettelClient: Reactive loop stopped");
                break;
            }

            // Poll with 50ms timeout — tight enough to be reactive
            let event = match self.fd.poll_event(50) {
                Ok(Some(ev)) => ev,
                Ok(None) => continue,
                Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => continue,
                Err(e) => {
                    eprintln!("⚠️  ApplettelClient: Poll error: {}", e);
                    break;
                }
            };

            let (msg_type, seq, payload) = event;

            match msg_type {
                LettingMsgType::FieldChanged => {
                    self.handle_field_changed(seq, &payload);
                }
                LettingMsgType::Ping => {
                    // Keepalive — nothing to do, host sent it
                    println!("🏓 ApplettelClient: Keepalive ping (seq={})", seq);
                }
                LettingMsgType::Disconnect => {
                    println!("📭 ApplettelClient: Host disconnected");
                    *self.running.lock().unwrap() = false;
                    break;
                }
                other => {
                    println!(
                        "📨 ApplettelClient: Unhandled msg type {:?} (seq={})",
                        other, seq
                    );
                }
            }
        }

        Ok(())
    }

    /// Stop the reactive loop from another thread
    pub fn stop(&self) {
        *self.running.lock().unwrap() = false;
        println!("🛑 ApplettelClient: Stop requested");
    }

    /// Process a FieldChanged event payload
    fn handle_field_changed(&self, seq: u32, payload: &[u8]) {
        // Payload: [field_key encoded][value_len:u32][value_bytes]
        let (field, consumed) = match FieldKey::decode(payload) {
            Some(r) => r,
            None => {
                eprintln!("⚠️  ApplettelClient: Failed to decode field key");
                return;
            }
        };

        if consumed + 4 > payload.len() {
            eprintln!("⚠️  ApplettelClient: Payload too short for value");
            return;
        }

        let val_len =
            u32::from_le_bytes(payload[consumed..consumed + 4].try_into().unwrap()) as usize;

        if consumed + 4 + val_len > payload.len() {
            eprintln!("⚠️  ApplettelClient: Value truncated");
            return;
        }

        let raw_val = payload[consumed + 4..consumed + 4 + val_len].to_vec();
        let new_value = FieldValue::new(raw_val, FieldTypeHint::Bytes);

        // Update cache, keep previous value
        let previous = {
            let mut cache = self.cache.lock().unwrap();
            cache.update(field.clone(), new_value.clone())
        };

        let event = LettingEvent {
            field: field.clone(),
            value: new_value,
            previous,
            seq,
            received_at: SystemTime::now(),
        };

        // Trigger all registered handlers for this field
        let handlers = self.handlers.lock().unwrap();
        if let Some(field_handlers) = handlers.get(&field) {
            for handler in field_handlers {
                handler(&event);
            }
        }
    }

    // -------------------------------------------------------------------------
    // KEEPALIVE
    // -------------------------------------------------------------------------

    /// Send ping to host, returns round-trip duration
    pub fn ping(&mut self) -> Result<Duration, String> {
        if !self.fd.is_connected() {
            return Err("Not connected".to_string());
        }
        let start = std::time::Instant::now();
        match self.fd.send(LettingMsgType::Ping, self.descriptor.id, &[]) {
            Ok((LettingStatus::Pong, _, _)) => Ok(start.elapsed()),
            Ok((status, _, _)) => Err(format!("Ping unexpected status: {:?}", status)),
            Err(e) => Err(format!("Ping error: {}", e)),
        }
    }

    // -------------------------------------------------------------------------
    // ACCESSORS
    // -------------------------------------------------------------------------

    pub fn applet_id(&self) -> u32 {
        self.descriptor.id
    }
    pub fn descriptor(&self) -> &AppletDescriptor {
        &self.descriptor
    }
    pub fn is_connected(&self) -> bool {
        self.fd.is_connected()
    }
    pub fn is_running(&self) -> bool {
        *self.running.lock().unwrap()
    }

    pub fn subscription_count(&self) -> usize {
        self.subscriptions.lock().unwrap().len()
    }

    pub fn cached_field_count(&self) -> usize {
        self.cache.lock().unwrap().len()
    }

    pub fn get_config(&self) -> &WasmaConfig {
        &self.config
    }
}

// ============================================================================
// BUILDER
// ============================================================================

pub struct ApplettelClientBuilder {
    config: Option<WasmaConfig>,
    descriptor: Option<AppletDescriptor>,
    socket_path: Option<String>,
    initial_subscriptions: Vec<(FieldKey, LettingHandler)>,
}

impl ApplettelClientBuilder {
    pub fn new() -> Self {
        Self {
            config: None,
            descriptor: None,
            socket_path: None,
            initial_subscriptions: Vec::new(),
        }
    }

    pub fn with_config(mut self, config: WasmaConfig) -> Self {
        self.config = Some(config);
        self
    }

    pub fn with_descriptor(mut self, desc: AppletDescriptor) -> Self {
        self.descriptor = Some(desc);
        self
    }

    pub fn with_socket(mut self, path: impl Into<String>) -> Self {
        self.socket_path = Some(path.into());
        self
    }

    pub fn subscribe_on_start(mut self, field: FieldKey, handler: LettingHandler) -> Self {
        self.initial_subscriptions.push((field, handler));
        self
    }

    pub fn build(self) -> Result<ApplettelClient, String> {
        let config = self.config.ok_or("Config required")?;
        let descriptor = self.descriptor.ok_or("AppletDescriptor required")?;

        let mut client = ApplettelClient::new(config, descriptor);

        if let Some(path) = self.socket_path {
            client.socket_path = path;
        }

        // Pre-register handlers (without sending to host yet — not connected)
        for (field, handler) in self.initial_subscriptions {
            let mut handlers = client.handlers.lock().unwrap();
            handlers.entry(field.clone()).or_default().push(handler);
            let mut subs = client.subscriptions.lock().unwrap();
            if !subs.contains(&field) {
                subs.push(field);
            }
        }

        Ok(client)
    }
}

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

// ============================================================================
// TESTS
// ============================================================================

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

    fn make_config() -> WasmaConfig {
        let parser = ConfigParser::new(None);
        let content = parser.generate_default_config();
        parser.parse(&content).unwrap()
    }

    fn make_system_descriptor() -> AppletDescriptor {
        AppletDescriptor::new(
            "test-tray",
            "1.0.0",
            AppletKind::System(SystemAppletRole::TrayIcon),
            "host.app",
        )
    }

    fn make_embedded_descriptor() -> AppletDescriptor {
        AppletDescriptor::new(
            "test-embed",
            "1.0.0",
            AppletKind::Embedded(EmbeddedAppletRole::SidePanel),
            "host.app",
        )
    }

    #[test]
    fn test_client_creation_system() {
        let config = make_config();
        let desc = make_system_descriptor();
        let client = ApplettelClient::new(config, desc);

        assert!(!client.is_connected());
        assert!(!client.is_running());
        assert_eq!(client.applet_id(), 0);
        assert!(client.descriptor().kind.is_system());

        println!("✅ System applet creation working");
    }

    #[test]
    fn test_client_creation_embedded() {
        let config = make_config();
        let desc = make_embedded_descriptor();
        let client = ApplettelClient::new(config, desc);

        assert!(client.descriptor().kind.is_embedded());
        println!("✅ Embedded applet creation working");
    }

    #[test]
    fn test_field_key_codec() {
        let key = FieldKey::new("window", "title");
        let encoded = key.encode();
        let (decoded, consumed) = FieldKey::decode(&encoded).unwrap();

        assert_eq!(decoded.namespace, "window");
        assert_eq!(decoded.name, "title");
        assert_eq!(consumed, encoded.len());

        println!("✅ FieldKey codec working");
    }

    #[test]
    fn test_field_key_codec_unicode() {
        // Test with longer keys
        let key = FieldKey::new("resource_manager", "cpu_usage_percentage");
        let encoded = key.encode();
        let (decoded, _) = FieldKey::decode(&encoded).unwrap();
        assert_eq!(decoded.namespace, "resource_manager");
        assert_eq!(decoded.name, "cpu_usage_percentage");
        println!("✅ FieldKey unicode/long codec working");
    }

    #[test]
    fn test_field_cache_operations() {
        let mut cache = FieldCache::new();
        let key = FieldKey::new("app", "state");

        assert!(cache.get(&key).is_none());

        let val1 = FieldValue::new(b"running".to_vec(), FieldTypeHint::String);
        let prev = cache.update(key.clone(), val1);
        assert!(prev.is_none());

        let val2 = FieldValue::new(b"paused".to_vec(), FieldTypeHint::String);
        let prev = cache.update(key.clone(), val2);
        assert!(prev.is_some());
        assert_eq!(prev.unwrap().as_str(), Some("running"));

        let current = cache.get(&key).unwrap();
        assert_eq!(current.as_str(), Some("paused"));

        cache.remove(&key);
        assert!(cache.get(&key).is_none());

        println!("✅ FieldCache operations working");
    }

    #[test]
    fn test_field_value_accessors() {
        let u64_val = FieldValue::new(42u64.to_le_bytes().to_vec(), FieldTypeHint::U64);
        assert_eq!(u64_val.as_u64(), Some(42));

        let f64_val = FieldValue::new(3.14f64.to_le_bytes().to_vec(), FieldTypeHint::F64);
        assert!((f64_val.as_f64().unwrap() - 3.14).abs() < f64::EPSILON);

        let str_val = FieldValue::new(b"hello".to_vec(), FieldTypeHint::String);
        assert_eq!(str_val.as_str(), Some("hello"));

        println!("✅ FieldValue accessors working");
    }

    #[test]
    fn test_handler_registration_via_builder() {
        let config = make_config();
        let desc = make_system_descriptor();
        let counter = Arc::new(AtomicU32::new(0));
        let counter_clone = counter.clone();

        let client = ApplettelClientBuilder::new()
            .with_config(config)
            .with_descriptor(desc)
            .with_socket("/run/wasma/test.sock")
            .subscribe_on_start(
                FieldKey::new("window", "title"),
                Arc::new(move |_event| {
                    counter_clone.fetch_add(1, Ordering::SeqCst);
                }),
            )
            .build()
            .unwrap();

        assert_eq!(client.subscription_count(), 1);
        println!("✅ Builder handler registration working");
    }

    #[test]
    fn test_handle_field_changed_triggers_handler() {
        let config = make_config();
        let desc = make_system_descriptor();
        let fired = Arc::new(AtomicU32::new(0));
        let fired_clone = fired.clone();

        let client = ApplettelClient::new(config, desc);

        // Manually register a handler
        let field = FieldKey::new("window", "state");
        {
            let mut handlers = client.handlers.lock().unwrap();
            handlers
                .entry(field.clone())
                .or_default()
                .push(Arc::new(move |event| {
                    fired_clone.fetch_add(1, Ordering::SeqCst);
                    assert_eq!(event.field.namespace, "window");
                    assert_eq!(event.field.name, "state");
                }));
        }

        // Simulate a FieldChanged payload
        let mut payload = field.encode();
        let val = b"maximized";
        payload.extend_from_slice(&(val.len() as u32).to_le_bytes());
        payload.extend_from_slice(val);

        client.handle_field_changed(1, &payload);

        assert_eq!(fired.load(Ordering::SeqCst), 1);
        assert_eq!(client.cached_field_count(), 1);
        println!("✅ Reactive handler trigger working");
    }

    #[test]
    fn test_handle_field_changed_updates_cache_with_previous() {
        let config = make_config();
        let desc = make_embedded_descriptor();
        let prev_seen = Arc::new(Mutex::new(Option::<Vec<u8>>::None));
        let prev_clone = prev_seen.clone();

        let client = ApplettelClient::new(config, desc);
        let field = FieldKey::new("resource", "cpu_usage");

        {
            let mut handlers = client.handlers.lock().unwrap();
            handlers
                .entry(field.clone())
                .or_default()
                .push(Arc::new(move |event| {
                    if let Some(ref prev) = event.previous {
                        *prev_clone.lock().unwrap() = Some(prev.raw.clone());
                    }
                }));
        }

        // First change — no previous
        let mut p1 = field.encode();
        p1.extend_from_slice(&4u32.to_le_bytes());
        p1.extend_from_slice(&42u32.to_le_bytes());
        client.handle_field_changed(1, &p1);
        assert!(prev_seen.lock().unwrap().is_none());

        // Second change — previous should be first value
        let mut p2 = field.encode();
        p2.extend_from_slice(&4u32.to_le_bytes());
        p2.extend_from_slice(&99u32.to_le_bytes());
        client.handle_field_changed(2, &p2);
        let prev = prev_seen.lock().unwrap().clone();
        assert!(prev.is_some());

        println!("✅ Previous value tracking working");
    }

    #[test]
    fn test_applet_kind_display() {
        let sys = AppletKind::System(SystemAppletRole::TrayIcon);
        let emb = AppletKind::Embedded(EmbeddedAppletRole::Inspector);

        assert!(sys.display_name().starts_with("system::"));
        assert!(emb.display_name().starts_with("embedded::"));
        assert!(sys.is_system());
        assert!(emb.is_embedded());
        assert!(!sys.is_embedded());
        assert!(!emb.is_system());

        println!("✅ AppletKind display working");
    }

    #[test]
    fn test_descriptor_encode() {
        let mut desc = make_system_descriptor();
        desc.host_window_id = Some(42);
        let encoded = desc.encode();
        assert!(!encoded.is_empty());
        // kind byte should be 0x01 for system
        // find it: after name(2+len) + ver(2+len) + host(2+len)
        println!(
            "✅ AppletDescriptor encode working ({} bytes)",
            encoded.len()
        );
    }

    #[test]
    fn test_stop_flag() {
        let config = make_config();
        let desc = make_system_descriptor();
        let client = ApplettelClient::new(config, desc);

        assert!(!client.is_running());
        *client.running.lock().unwrap() = true;
        assert!(client.is_running());
        client.stop();
        assert!(!client.is_running());

        println!("✅ Stop flag working");
    }
}