clasp-client 4.4.0

CLASP client library
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
//! Client Library Tests (clasp-client)
//!
//! Tests for the high-level Clasp client API including:
//! - Builder pattern and configuration
//! - Connection lifecycle
//! - Parameter operations (set, get, subscribe)
//! - Event operations (emit, subscribe)
//! - Advanced features (bundles, caching, clock sync)
//! - Negative tests and edge cases
//! - Value type coverage

use clasp_client::{Clasp, ClaspBuilder};
use clasp_core::{Message, SetMessage, Value};
use clasp_test_utils::{TestRouter, ValueCollector};
use std::time::Duration;
use tokio::time::timeout;

// ============================================================================
// Builder Tests
// ============================================================================

#[tokio::test]
async fn test_builder_default() {
    let router = TestRouter::start().await;

    let client = ClaspBuilder::new(&router.url())
        .connect()
        .await
        .expect("Connect failed");

    assert!(client.is_connected(), "Client not connected");
    assert!(client.session_id().is_some(), "No session ID");

    client.close().await;
}

#[tokio::test]
async fn test_builder_custom_name() {
    let router = TestRouter::start().await;

    let custom_name = "MyCustomTestClient";
    let client = ClaspBuilder::new(&router.url())
        .name(custom_name)
        .connect()
        .await
        .expect("Connect failed");

    assert!(client.is_connected(), "Client not connected");

    client.close().await;
}

#[tokio::test]
async fn test_builder_features() {
    let router = TestRouter::start().await;

    let client = ClaspBuilder::new(&router.url())
        .features(vec![
            "param".to_string(),
            "event".to_string(),
            "stream".to_string(),
            "gesture".to_string(),
        ])
        .connect()
        .await
        .expect("Connect failed");

    assert!(client.is_connected(), "Client not connected");

    client.close().await;
}

#[tokio::test]
async fn test_builder_chained() {
    let router = TestRouter::start().await;

    let client = ClaspBuilder::new(&router.url())
        .name("ChainedBuilder")
        .features(vec!["param".to_string(), "event".to_string()])
        .reconnect(false)
        .reconnect_interval(1000)
        .connect()
        .await
        .expect("Connect failed");

    assert!(client.is_connected(), "Client not connected");

    client.close().await;
}

// ============================================================================
// Connection Lifecycle Tests
// ============================================================================

#[tokio::test]
async fn test_connect_to() {
    let router = TestRouter::start().await;

    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    assert!(client.is_connected(), "Client not connected");
    assert!(client.session_id().is_some(), "No session ID");

    client.close().await;
}

#[tokio::test]
async fn test_session_id() {
    let router = TestRouter::start().await;

    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let session_id = client.session_id().expect("No session ID");
    assert!(!session_id.is_empty(), "Session ID is empty");
    assert_eq!(session_id.len(), 36, "Session ID should be UUID format");

    client.close().await;
}

#[tokio::test]
async fn test_graceful_disconnect() {
    let router = TestRouter::start().await;

    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    assert!(client.is_connected(), "Should be connected");

    client.close().await;

    assert!(
        !client.is_connected(),
        "Should not be connected after close"
    );
}

#[tokio::test]
async fn test_connection_error_nonexistent() {
    let connect_result = timeout(
        Duration::from_secs(3),
        Clasp::connect_to("ws://127.0.0.1:1"),
    )
    .await;

    match connect_result {
        Ok(Ok(_)) => panic!("Should have failed to connect to nonexistent server"),
        Ok(Err(_)) => {} // Expected: connection error
        Err(_) => {}     // Expected: timeout
    }
}

#[tokio::test]
async fn test_connection_error_invalid_url() {
    let invalid_urls = vec!["not-a-url", "http://localhost", "", "ftp://server"];

    for url in invalid_urls {
        let connect_result = timeout(Duration::from_secs(2), Clasp::connect_to(url)).await;

        if let Ok(Ok(_)) = connect_result {
            panic!("Should have failed for invalid URL: {}", url);
        }
    }
}

// ============================================================================
// Parameter Operations Tests
// ============================================================================

#[tokio::test]
async fn test_set_parameter() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    client.set("/test/value", 42.0).await.expect("Set failed");

    client.close().await;
}

#[tokio::test]
async fn test_set_and_receive() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();

    client
        .subscribe("/test/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    client
        .set("/test/sensor", 123.456)
        .await
        .expect("Set failed");

    // Wait for the value with timeout
    let received = collector.wait_for_count(1, Duration::from_secs(2)).await;
    assert!(received, "Did not receive SET value within timeout");

    // Verify the value
    let values = collector.values();
    let (addr, value) = values.last().expect("No value received");
    assert_eq!(addr, "/test/sensor");
    let f = value.as_f64().expect("Value is not a float");
    assert!((f - 123.456).abs() < 0.001, "Value mismatch");

    client.close().await;
}

#[tokio::test]
async fn test_set_locked() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    client
        .set_locked("/test/locked", 100.0)
        .await
        .expect("Set locked failed");

    client.close().await;
}

#[tokio::test]
async fn test_subscribe_pattern_wildcard() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();

    client
        .subscribe("/sensors/*", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    // Send to matching addresses
    client.set("/sensors/temp", 25.0).await.expect("Set failed");
    client
        .set("/sensors/humidity", 60.0)
        .await
        .expect("Set failed");
    client
        .set("/sensors/pressure", 1013.25)
        .await
        .expect("Set failed");

    // Wait for all three
    let received = collector.wait_for_count(3, Duration::from_secs(2)).await;
    assert!(received, "Did not receive all 3 values");

    // Verify all addresses received
    assert!(
        collector.has_address("/sensors/temp"),
        "Missing /sensors/temp"
    );
    assert!(
        collector.has_address("/sensors/humidity"),
        "Missing /sensors/humidity"
    );
    assert!(
        collector.has_address("/sensors/pressure"),
        "Missing /sensors/pressure"
    );

    client.close().await;
}

#[tokio::test]
async fn test_subscribe_pattern_globstar() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();

    // ** should match any depth
    client
        .subscribe("/app/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    client.set("/app/level1", 1.0).await.expect("Set failed");
    client
        .set("/app/level1/level2", 2.0)
        .await
        .expect("Set failed");
    client.set("/app/a/b/c/d", 4.0).await.expect("Set failed");

    let received = collector.wait_for_count(3, Duration::from_secs(2)).await;
    assert!(received, "Did not receive all globstar values");

    client.close().await;
}

#[tokio::test]
async fn test_unsubscribe() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();

    let sub_id = client
        .subscribe("/unsub/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    // Send one value
    client.set("/unsub/before", 1.0).await.expect("Set failed");
    collector.wait_for_count(1, Duration::from_secs(1)).await;
    let count_before = collector.count();

    // Unsubscribe
    client
        .unsubscribe(sub_id)
        .await
        .expect("Unsubscribe failed");

    // Small delay for unsubscribe to propagate
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Send more values - should not be received
    client.set("/unsub/after1", 2.0).await.expect("Set failed");
    client.set("/unsub/after2", 3.0).await.expect("Set failed");

    tokio::time::sleep(Duration::from_millis(100)).await;

    let count_after = collector.count();

    // Count should not have increased significantly after unsubscribe
    assert!(
        count_after <= count_before + 1,
        "Received values after unsubscribe: before={}, after={}",
        count_before,
        count_after
    );

    client.close().await;
}

#[tokio::test]
async fn test_cached_value() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();

    client
        .subscribe("/cache/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    client.set("/cache/test", 42.0).await.expect("Set failed");

    collector.wait_for_count(1, Duration::from_secs(2)).await;

    // Check cached value
    let cached = client.cached("/cache/test");
    if let Some(v) = cached {
        let f = v.as_f64().expect("Cached value not a float");
        assert!((f - 42.0).abs() < 0.001, "Cached value mismatch");
    }
    // Note: Cache might not be populated if the value arrives asynchronously
    // This test verifies the cache API works, not that it's always populated

    client.close().await;
}

// ============================================================================
// Event Operations Tests
// ============================================================================

#[tokio::test]
async fn test_emit_event() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    client
        .emit("/events/button", Value::String("pressed".to_string()))
        .await
        .expect("Emit failed");

    client.close().await;
}

#[tokio::test]
async fn test_emit_and_receive() {
    let router = TestRouter::start().await;

    // Two clients: one emits, one receives
    let receiver = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");
    let emitter = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();

    receiver
        .subscribe("/events/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    tokio::time::sleep(Duration::from_millis(50)).await;

    emitter
        .emit("/events/trigger", Value::String("activated".to_string()))
        .await
        .expect("Emit failed");

    let received = collector.wait_for_count(1, Duration::from_secs(2)).await;
    assert!(received, "Event not received");

    assert!(
        collector.has_address("/events/trigger"),
        "Wrong event address"
    );

    receiver.close().await;
    emitter.close().await;
}

#[tokio::test]
async fn test_stream() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    // Stream sends multiple samples
    for i in 0..10 {
        client
            .stream("/sensors/accel", Value::Float(i as f64 * 0.1))
            .await
            .unwrap_or_else(|_| panic!("Stream {} failed", i));
    }

    client.close().await;
}

// ============================================================================
// Advanced Features Tests
// ============================================================================

#[tokio::test]
async fn test_bundle() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let messages = vec![
        Message::Set(SetMessage {
            address: "/bundle/a".to_string(),
            value: Value::Int(1),
            revision: None,
            lock: false,
            unlock: false,
            ttl: None,
        }),
        Message::Set(SetMessage {
            address: "/bundle/b".to_string(),
            value: Value::Int(2),
            revision: None,
            lock: false,
            unlock: false,
            ttl: None,
        }),
        Message::Set(SetMessage {
            address: "/bundle/c".to_string(),
            value: Value::Int(3),
            revision: None,
            lock: false,
            unlock: false,
            ttl: None,
        }),
    ];

    client.bundle(messages).await.expect("Bundle failed");

    client.close().await;
}

#[tokio::test]
async fn test_bundle_atomicity() {
    let router = TestRouter::start().await;

    let sender = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");
    let receiver = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();
    receiver
        .subscribe("/atomic/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");
    tokio::time::sleep(Duration::from_millis(50)).await;

    // Send bundle of 5 values
    let messages: Vec<Message> = (0..5)
        .map(|i| {
            Message::Set(SetMessage {
                address: format!("/atomic/v{}", i),
                value: Value::Int(i),
                revision: None,
                lock: false,
                unlock: false,
                ttl: None,
            })
        })
        .collect();

    sender.bundle(messages).await.expect("Bundle failed");

    // Should receive all 5
    let received = collector.wait_for_count(5, Duration::from_secs(2)).await;
    assert!(received, "Did not receive all bundle values");

    sender.close().await;
    receiver.close().await;
}

#[tokio::test]
async fn test_bundle_at() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let messages = vec![Message::Set(SetMessage {
        address: "/scheduled/value".to_string(),
        value: Value::Float(99.9),
        revision: None,
        lock: false,
        unlock: false,
        ttl: None,
    })];

    let future_time = client.time() + 100_000; // 100ms in microseconds
    client
        .bundle_at(messages, future_time)
        .await
        .expect("Bundle_at failed");

    client.close().await;
}

#[tokio::test]
async fn test_clock_sync() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let server_time = client.time();

    // Should be a reasonable timestamp (non-zero, in microseconds)
    assert!(server_time > 0, "Server time should be positive");

    // Should be roughly recent (within last hour of current time in microseconds)
    let now_micros = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_micros() as i64;

    let diff = (server_time as i64 - now_micros).abs();
    // Allow up to 1 hour difference for any sync offset
    assert!(
        diff < 3_600_000_000,
        "Server time too far from local: diff={}",
        diff
    );

    client.close().await;
}

// ============================================================================
// Value Type Tests
// ============================================================================

#[tokio::test]
async fn test_value_type_int() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();
    client
        .subscribe("/types/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    client.set("/types/int", 42i64).await.expect("Set failed");
    client
        .set("/types/int_neg", -100i64)
        .await
        .expect("Set failed");
    client
        .set("/types/int_zero", 0i64)
        .await
        .expect("Set failed");
    client
        .set("/types/int_max", i64::MAX)
        .await
        .expect("Set failed");

    collector.wait_for_count(4, Duration::from_secs(2)).await;

    client.close().await;
}

#[tokio::test]
async fn test_value_type_float() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();
    client
        .subscribe("/types/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    client
        .set("/types/float", 1.2345f64)
        .await
        .expect("Set failed");
    client
        .set("/types/float_neg", -273.15f64)
        .await
        .expect("Set failed");
    client
        .set("/types/float_zero", 0.0f64)
        .await
        .expect("Set failed");
    client
        .set("/types/float_tiny", 1e-100f64)
        .await
        .expect("Set failed");

    collector.wait_for_count(4, Duration::from_secs(2)).await;

    client.close().await;
}

#[tokio::test]
async fn test_value_type_bool() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();
    client
        .subscribe("/types/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    client
        .set("/types/bool_true", true)
        .await
        .expect("Set failed");
    client
        .set("/types/bool_false", false)
        .await
        .expect("Set failed");

    let received = collector.wait_for_count(2, Duration::from_secs(2)).await;
    assert!(received, "Did not receive bool values");

    client.close().await;
}

#[tokio::test]
async fn test_value_type_string() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();
    client
        .subscribe("/types/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    client
        .set("/types/str", "hello world")
        .await
        .expect("Set failed");
    client
        .set("/types/str_empty", "")
        .await
        .expect("Set failed");
    client
        .set("/types/str_unicode", "Hello, \u{1F30D}!")
        .await
        .expect("Set failed");
    client
        .set("/types/str_long", "x".repeat(1000))
        .await
        .expect("Set failed");

    collector.wait_for_count(4, Duration::from_secs(2)).await;

    client.close().await;
}

#[tokio::test]
async fn test_value_type_bytes() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    client
        .set(
            "/types/bytes",
            Value::Bytes(vec![0x00, 0xFF, 0x42, 0xDE, 0xAD]),
        )
        .await
        .expect("Set failed");
    client
        .set("/types/bytes_empty", Value::Bytes(vec![]))
        .await
        .expect("Set failed");

    client.close().await;
}

#[tokio::test]
async fn test_value_type_array() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    client
        .set(
            "/types/array",
            Value::Array(vec![Value::Int(1), Value::Int(2), Value::Int(3)]),
        )
        .await
        .expect("Set failed");

    client
        .set(
            "/types/array_mixed",
            Value::Array(vec![
                Value::Int(1),
                Value::Float(2.5),
                Value::String("three".to_string()),
            ]),
        )
        .await
        .expect("Set failed");

    client
        .set("/types/array_empty", Value::Array(vec![]))
        .await
        .expect("Set failed");

    client.close().await;
}

#[tokio::test]
async fn test_value_type_null() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    client
        .set("/types/null", Value::Null)
        .await
        .expect("Set failed");

    client.close().await;
}

// ============================================================================
// Two-Client Interaction Tests
// ============================================================================

#[tokio::test]
async fn test_two_client_set_receive() {
    let router = TestRouter::start().await;

    let client1 = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");
    let client2 = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector = ValueCollector::new();

    client1
        .subscribe("/shared/**", collector.callback_ref())
        .await
        .expect("Subscribe failed");

    tokio::time::sleep(Duration::from_millis(50)).await;

    client2
        .set("/shared/value", 42.0)
        .await
        .expect("Set failed");

    let received = collector.wait_for_count(1, Duration::from_secs(2)).await;
    assert!(received, "Client 1 did not receive value from Client 2");

    client1.close().await;
    client2.close().await;
}

#[tokio::test]
async fn test_bidirectional_communication() {
    let router = TestRouter::start().await;

    let client1 = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");
    let client2 = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    let collector1 = ValueCollector::new();
    let collector2 = ValueCollector::new();

    client1
        .subscribe("/from2/**", collector1.callback_ref())
        .await
        .expect("Subscribe failed");
    client2
        .subscribe("/from1/**", collector2.callback_ref())
        .await
        .expect("Subscribe failed");

    tokio::time::sleep(Duration::from_millis(50)).await;

    // Bidirectional sends
    client1
        .set("/from1/message", 100.0)
        .await
        .expect("Set failed");
    client2
        .set("/from2/message", 200.0)
        .await
        .expect("Set failed");

    let recv1 = collector1.wait_for_count(1, Duration::from_secs(2)).await;
    let recv2 = collector2.wait_for_count(1, Duration::from_secs(2)).await;

    assert!(recv1, "Client1 did not receive from Client2");
    assert!(recv2, "Client2 did not receive from Client1");

    client1.close().await;
    client2.close().await;
}

// ============================================================================
// Concurrent Operations Tests
// ============================================================================

#[tokio::test]
async fn test_concurrent_operations() {
    let router = TestRouter::start().await;

    let mut clients = vec![];
    for i in 0..5 {
        let client = Clasp::builder(&router.url())
            .name(&format!("ConcurrentClient{}", i))
            .connect()
            .await
            .expect("Connect failed");
        clients.push(client);
    }

    let mut success_count = 0;
    for (i, client) in clients.iter().enumerate() {
        for j in 0..5 {
            if client
                .set(&format!("/concurrent/{}/{}", i, j), (i * 10 + j) as f64)
                .await
                .is_ok()
            {
                success_count += 1;
            }
        }
    }

    assert!(
        success_count >= 20,
        "Only {}/25 concurrent operations succeeded",
        success_count
    );

    for client in clients {
        client.close().await;
    }
}

#[tokio::test]
async fn test_rapid_subscribe_unsubscribe() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    for i in 0..20 {
        let collector = ValueCollector::new();
        let sub_id = client
            .subscribe(&format!("/rapid/{}", i), collector.callback_ref())
            .await
            .expect("Subscribe failed");
        client
            .unsubscribe(sub_id)
            .await
            .expect("Unsubscribe failed");
    }

    client.close().await;
}

// ============================================================================
// Edge Case and Negative Tests
// ============================================================================

#[tokio::test]
async fn test_operations_before_connect() {
    // This test verifies that builder state is clean before connect
    let router = TestRouter::start().await;

    // Build client but don't connect yet
    let builder = ClaspBuilder::new(&router.url()).name("PreConnect");

    // Now connect and verify it works
    let client = builder.connect().await.expect("Connect failed");
    assert!(client.is_connected(), "Should be connected");

    client.close().await;
}

#[tokio::test]
async fn test_operations_after_close() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    client.close().await;

    // These should not panic
    assert!(!client.is_connected(), "Should not be connected");
    let _ = client.set("/test", 1.0).await;
    let _ = client.subscribe("/test", |_, _| {}).await;
}

#[tokio::test]
async fn test_double_close() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    client.close().await;
    client.close().await; // Should not panic

    assert!(!client.is_connected(), "Should not be connected");
}

#[tokio::test]
async fn test_special_characters_in_address() {
    let router = TestRouter::start().await;
    let client = Clasp::connect_to(&router.url())
        .await
        .expect("Connect failed");

    // Various address formats
    client.set("/simple", 1.0).await.expect("Set failed");
    client.set("/with-dash", 2.0).await.expect("Set failed");
    client
        .set("/with_underscore", 3.0)
        .await
        .expect("Set failed");
    client.set("/with.dot", 4.0).await.expect("Set failed");
    client.set("/CamelCase", 5.0).await.expect("Set failed");
    client
        .set("/with123numbers", 6.0)
        .await
        .expect("Set failed");

    client.close().await;
}