plexus-core 0.5.3

Core infrastructure for Plexus RPC: Activation trait, DynamicHub, schemas
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
//! Unit tests for bidirectional communication primitives
//!
//! These tests verify the core bidirectional channel functionality:
//! - BidirChannel request/response flow
//! - Global registry behavior (register, unregister, handle_pending_response)
//! - Timeout scenarios
//! - Error handling

use plexus_core::plexus::bidirectional::{
    auto_confirm_channel, auto_respond_channel, bidir_error_message, create_test_bidir_channel,
    create_test_standard_channel, handle_pending_response, is_request_pending, pending_count,
    register_pending_request, unregister_pending_request, BidirChannel, BidirError,
    BidirWithFallback, SelectOption, StandardBidirChannel, StandardRequest, StandardResponse,
    TimeoutConfig,
};
use plexus_core::plexus::types::PlexusStreamItem;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};

// =============================================================================
// BidirChannel Basic Tests
// =============================================================================

#[tokio::test]
async fn test_bidir_channel_creation() {
    let (tx, _rx) = mpsc::channel(32);
    let channel: StandardBidirChannel =
        BidirChannel::new_direct(tx, true, vec!["test".into()], "hash123".into());

    assert!(channel.is_bidirectional());
    assert_eq!(channel.provenance(), &["test"]);
    assert_eq!(channel.plexus_hash(), "hash123");
}

#[tokio::test]
async fn test_bidir_channel_not_supported() {
    let (tx, _rx) = mpsc::channel(32);
    let channel: StandardBidirChannel =
        BidirChannel::new_direct(tx, false, vec![], "hash".into());

    assert!(!channel.is_bidirectional());

    let result = channel.confirm("Test?").await;
    assert!(matches!(result, Err(BidirError::NotSupported)));
}

#[tokio::test]
async fn test_bidir_channel_direct_flow() {
    let (tx, mut rx) = mpsc::channel(32);
    let channel: Arc<StandardBidirChannel> =
        Arc::new(BidirChannel::new_direct(tx, true, vec![], "hash".into()));

    let channel_clone = channel.clone();
    let handle = tokio::spawn(async move { channel_clone.confirm("Delete?").await });

    // Process request
    if let Some(PlexusStreamItem::Request {
        request_id,
        request_data,
        timeout_ms,
    }) = rx.recv().await
    {
        // Verify request structure
        assert!(!request_id.is_empty());
        assert_eq!(timeout_ms, 30000); // Default timeout

        let req: StandardRequest = serde_json::from_value(request_data).unwrap();
        assert!(matches!(req, StandardRequest::Confirm { message, .. } if message == "Delete?"));

        // Send response
        channel
            .handle_response(
                request_id,
                serde_json::to_value(&StandardResponse::<serde_json::Value>::Confirmed {
                    value: true,
                })
                .unwrap(),
            )
            .unwrap();
    }

    let result = handle.await.unwrap().unwrap();
    assert!(result);
}

#[tokio::test]
async fn test_bidir_channel_prompt_flow() {
    let (tx, mut rx) = mpsc::channel(32);
    let channel: Arc<StandardBidirChannel> =
        Arc::new(BidirChannel::new_direct(tx, true, vec![], "hash".into()));

    let channel_clone = channel.clone();
    let handle = tokio::spawn(async move { channel_clone.prompt("Name?").await });

    if let Some(PlexusStreamItem::Request { request_id, .. }) = rx.recv().await {
        channel
            .handle_response(
                request_id,
                serde_json::to_value(&StandardResponse::<serde_json::Value>::Text {
                    value: serde_json::Value::String("Alice".into()),
                })
                .unwrap(),
            )
            .unwrap();
    }

    assert_eq!(handle.await.unwrap().unwrap(), "Alice");
}

#[tokio::test]
async fn test_bidir_channel_select_flow() {
    let (tx, mut rx) = mpsc::channel(32);
    let channel: Arc<StandardBidirChannel> =
        Arc::new(BidirChannel::new_direct(tx, true, vec![], "hash".into()));

    let channel_clone = channel.clone();
    let handle = tokio::spawn(async move {
        let options = vec![
            SelectOption::new("a", "Option A"),
            SelectOption::new("b", "Option B"),
        ];
        channel_clone.select("Choose:", options).await
    });

    if let Some(PlexusStreamItem::Request { request_id, .. }) = rx.recv().await {
        channel
            .handle_response(
                request_id,
                serde_json::to_value(&StandardResponse::<serde_json::Value>::Selected {
                    values: vec![serde_json::Value::String("b".into())],
                })
                .unwrap(),
            )
            .unwrap();
    }

    assert_eq!(handle.await.unwrap().unwrap(), vec!["b".to_string()]);
}

#[tokio::test]
async fn test_bidir_channel_cancelled_response() {
    let (tx, mut rx) = mpsc::channel(32);
    let channel: Arc<StandardBidirChannel> =
        Arc::new(BidirChannel::new_direct(tx, true, vec![], "hash".into()));

    let channel_clone = channel.clone();
    let handle = tokio::spawn(async move { channel_clone.confirm("Test?").await });

    if let Some(PlexusStreamItem::Request { request_id, .. }) = rx.recv().await {
        channel
            .handle_response(
                request_id,
                serde_json::to_value(&StandardResponse::<serde_json::Value>::Cancelled).unwrap(),
            )
            .unwrap();
    }

    let result = handle.await.unwrap();
    assert!(matches!(result, Err(BidirError::Cancelled)));
}

// =============================================================================
// Timeout Tests
// =============================================================================

#[tokio::test]
async fn test_bidir_channel_timeout() {
    let (tx, _rx) = mpsc::channel(32);
    let channel: StandardBidirChannel =
        BidirChannel::new_direct(tx, true, vec![], "hash".into());

    let start = std::time::Instant::now();
    let result = channel
        .request_with_timeout(
            StandardRequest::Confirm {
                message: "Test?".into(),
                default: None,
            },
            Duration::from_millis(50),
        )
        .await;

    let elapsed = start.elapsed();
    assert!(matches!(result, Err(BidirError::Timeout(50))));
    assert!(elapsed >= Duration::from_millis(45));
    assert!(elapsed < Duration::from_millis(150));
}

#[tokio::test]
async fn test_bidir_channel_custom_timeout() {
    let (tx, _rx) = mpsc::channel(32);
    let channel: StandardBidirChannel =
        BidirChannel::new_direct(tx, true, vec![], "hash".into());

    let result = channel
        .request_with_timeout(
            StandardRequest::Prompt {
                message: "?".into(),
                default: None,
                placeholder: None,
            },
            Duration::from_millis(25),
        )
        .await;

    assert!(matches!(result, Err(BidirError::Timeout(25))));
}

// =============================================================================
// Global Registry Tests
// =============================================================================

#[tokio::test]
async fn test_registry_register_and_handle() {
    let (tx, rx) = oneshot::channel::<Value>();
    let request_id = format!("test-{}", uuid::Uuid::new_v4());

    // Register
    register_pending_request(request_id.clone(), tx);
    assert!(is_request_pending(&request_id));

    // Handle response
    let response = serde_json::json!({"status": "ok"});
    handle_pending_response(&request_id, response.clone()).unwrap();

    // Verify response received
    let received = rx.await.unwrap();
    assert_eq!(received, response);

    // Should be removed
    assert!(!is_request_pending(&request_id));
}

#[tokio::test]
async fn test_registry_unknown_request() {
    let result = handle_pending_response("unknown-request-id", serde_json::json!({}));
    assert!(matches!(result, Err(BidirError::UnknownRequest)));
}

#[tokio::test]
async fn test_registry_unregister() {
    let (tx, _rx) = oneshot::channel::<Value>();
    let request_id = format!("test-unregister-{}", uuid::Uuid::new_v4());

    register_pending_request(request_id.clone(), tx);
    assert!(is_request_pending(&request_id));

    let removed = unregister_pending_request(&request_id);
    assert!(removed.is_some());
    assert!(!is_request_pending(&request_id));

    // Double unregister returns None
    let removed_again = unregister_pending_request(&request_id);
    assert!(removed_again.is_none());
}

#[tokio::test]
async fn test_registry_channel_closed() {
    let (tx, rx) = oneshot::channel::<Value>();
    let request_id = format!("test-closed-{}", uuid::Uuid::new_v4());

    register_pending_request(request_id.clone(), tx);

    // Drop receiver
    drop(rx);

    // Handle should fail with ChannelClosed
    let result = handle_pending_response(&request_id, serde_json::json!({}));
    assert!(matches!(result, Err(BidirError::ChannelClosed)));
}

#[tokio::test]
async fn test_registry_pending_count() {
    // Note: pending_count() reflects global state shared across concurrent tests,
    // so we only assert on per-ID presence rather than exact counts.
    let (tx1, _rx1) = oneshot::channel::<Value>();
    let (tx2, _rx2) = oneshot::channel::<Value>();
    let id1 = format!("count-test-1-{}", uuid::Uuid::new_v4());
    let id2 = format!("count-test-2-{}", uuid::Uuid::new_v4());

    assert!(!is_request_pending(&id1));
    assert!(!is_request_pending(&id2));

    register_pending_request(id1.clone(), tx1);
    assert!(is_request_pending(&id1));

    register_pending_request(id2.clone(), tx2);
    assert!(is_request_pending(&id2));

    // Count must be at least 2 (our entries), but may be higher due to concurrent tests
    assert!(pending_count() >= 2);

    unregister_pending_request(&id1);
    assert!(!is_request_pending(&id1));
    assert!(is_request_pending(&id2));

    unregister_pending_request(&id2);
    assert!(!is_request_pending(&id1));
    assert!(!is_request_pending(&id2));
}

#[tokio::test]
async fn test_registry_concurrent_requests() {
    let mut handles = Vec::new();
    let mut ids = Vec::new();

    // Register multiple requests
    for i in 0..10 {
        let (tx, rx) = oneshot::channel::<Value>();
        let id = format!("concurrent-{}-{}", i, uuid::Uuid::new_v4());
        ids.push(id.clone());
        register_pending_request(id.clone(), tx);

        handles.push(tokio::spawn(async move { rx.await }));
    }

    // All 10 should be individually pending
    for id in &ids {
        assert!(is_request_pending(id));
    }

    // Handle all responses
    for id in &ids {
        handle_pending_response(id, serde_json::json!({"id": id})).unwrap();
    }

    // All 10 should be individually removed
    for id in &ids {
        assert!(!is_request_pending(id));
    }

    // All receivers should have received their responses
    for handle in handles {
        assert!(handle.await.unwrap().is_ok());
    }
}

// =============================================================================
// BidirWithFallback Tests
// =============================================================================

#[tokio::test]
async fn test_fallback_when_not_supported() {
    let (tx, _rx) = mpsc::channel(32);
    let channel = Arc::new(BidirChannel::new_direct(
        tx, false, // not supported
        vec![],
        "hash".into(),
    ));

    let fallback = BidirWithFallback::auto_confirm(channel);

    // Should use fallback (auto-confirm true) when bidirectional not supported
    let resp = fallback
        .request(StandardRequest::Confirm {
            message: "Test?".into(),
            default: None,
        })
        .await;

    assert_eq!(resp, StandardResponse::Confirmed { value: true });
}

#[tokio::test]
async fn test_fallback_uses_default_value() {
    let (tx, _rx) = mpsc::channel(32);
    let channel = Arc::new(BidirChannel::new_direct(tx, false, vec![], "hash".into()));

    let fallback = BidirWithFallback::auto_confirm(channel);

    // With explicit default=false, should use that
    let resp = fallback
        .request(StandardRequest::Confirm {
            message: "Test?".into(),
            default: Some(false),
        })
        .await;

    assert_eq!(resp, StandardResponse::Confirmed { value: false });
}

#[tokio::test]
async fn test_fallback_prompt_uses_default() {
    let (tx, _rx) = mpsc::channel(32);
    let channel = Arc::new(BidirChannel::new_direct(tx, false, vec![], "hash".into()));

    let fallback = BidirWithFallback::auto_confirm(channel);

    let resp = fallback
        .request(StandardRequest::Prompt {
            message: "Name?".into(),
            default: Some(serde_json::Value::String("DefaultName".into())),
            placeholder: None,
        })
        .await;

    assert_eq!(
        resp,
        StandardResponse::Text {
            value: serde_json::Value::String("DefaultName".into()),
        }
    );
}

#[tokio::test]
async fn test_fallback_select_uses_first_option() {
    let (tx, _rx) = mpsc::channel(32);
    let channel = Arc::new(BidirChannel::new_direct(tx, false, vec![], "hash".into()));

    let fallback = BidirWithFallback::auto_confirm(channel);

    let resp = fallback
        .request(StandardRequest::Select {
            message: "Choose:".into(),
            options: vec![
                SelectOption::new("first", "First"),
                SelectOption::new("second", "Second"),
            ],
            multi_select: false,
        })
        .await;

    assert_eq!(
        resp,
        StandardResponse::Selected {
            values: vec![serde_json::Value::String("first".into())],
        }
    );
}

#[tokio::test]
async fn test_fallback_custom_function() {
    let (tx, _rx) = mpsc::channel(32);
    let channel = Arc::new(BidirChannel::new_direct(tx, false, vec![], "hash".into()));

    let fallback = BidirWithFallback::new(channel, |req: &StandardRequest| {
        match req {
            StandardRequest::Confirm { .. } => StandardResponse::Confirmed { value: false }, // Always decline
            StandardRequest::Prompt { .. } => StandardResponse::Text {
                value: serde_json::Value::String("custom".into()),
            },
            StandardRequest::Select { .. } => StandardResponse::Selected {
                values: vec![serde_json::Value::String("custom".into())],
            },
            StandardRequest::Custom { data } => StandardResponse::Custom { data: data.clone() },
        }
    });

    let resp = fallback
        .request(StandardRequest::Confirm {
            message: "Test?".into(),
            default: None,
        })
        .await;

    assert_eq!(resp, StandardResponse::Confirmed { value: false });
}

// =============================================================================
// Helper Function Tests
// =============================================================================

#[tokio::test]
async fn test_create_test_bidir_channel() {
    let (channel, _rx) = create_test_bidir_channel::<StandardRequest, StandardResponse>();
    assert!(channel.is_bidirectional());
    assert_eq!(channel.provenance(), &["test"]);
    assert_eq!(channel.plexus_hash(), "test-hash");
}

#[tokio::test]
async fn test_create_test_standard_channel() {
    let (channel, _rx) = create_test_standard_channel();
    assert!(channel.is_bidirectional());
}

#[tokio::test]
async fn test_auto_respond_channel() {
    let ctx = auto_respond_channel(|req: &StandardRequest| match req {
        StandardRequest::Confirm { .. } => StandardResponse::Confirmed { value: true },
        StandardRequest::Prompt { message, .. } => StandardResponse::Text {
            value: serde_json::Value::String(message.clone()),
        },
        StandardRequest::Select { options, .. } => StandardResponse::Selected {
            values: vec![options[0].value.clone()],
        },
        StandardRequest::Custom { data } => StandardResponse::Custom { data: data.clone() },
    });

    assert_eq!(ctx.confirm("Test?").await.unwrap(), true);
    assert_eq!(ctx.prompt("Echo this").await.unwrap(), "Echo this");

    let selected = ctx
        .select(
            "Pick:",
            vec![SelectOption::new("a", "A"), SelectOption::new("b", "B")],
        )
        .await
        .unwrap();
    assert_eq!(selected, vec!["a".to_string()]);
}

#[tokio::test]
async fn test_auto_confirm_channel_true() {
    let ctx = auto_confirm_channel(true);

    assert_eq!(ctx.confirm("Test?").await.unwrap(), true);
    assert_eq!(ctx.confirm("Another?").await.unwrap(), true);
}

#[tokio::test]
async fn test_auto_confirm_channel_false() {
    let ctx = auto_confirm_channel(false);

    assert_eq!(ctx.confirm("Test?").await.unwrap(), false);
}

#[tokio::test]
async fn test_auto_confirm_channel_respects_default() {
    let ctx = auto_confirm_channel(true);

    // With explicit default=false, should use the default
    let channel_clone = ctx.clone();
    let handle = tokio::spawn(async move {
        channel_clone
            .request(StandardRequest::Confirm {
                message: "Test?".into(),
                default: Some(false),
            })
            .await
    });

    let result = handle.await.unwrap().unwrap();
    assert_eq!(result, StandardResponse::Confirmed { value: false });
}

// =============================================================================
// TimeoutConfig Tests
// =============================================================================

#[test]
fn test_timeout_config_quick() {
    let config = TimeoutConfig::quick();
    assert_eq!(config.confirm, Duration::from_secs(10));
    assert_eq!(config.prompt, Duration::from_secs(10));
    assert_eq!(config.select, Duration::from_secs(10));
    assert_eq!(config.custom, Duration::from_secs(10));
}

#[test]
fn test_timeout_config_normal() {
    let config = TimeoutConfig::normal();
    assert_eq!(config.confirm, Duration::from_secs(30));
    assert_eq!(config.prompt, Duration::from_secs(30));
    assert_eq!(config.select, Duration::from_secs(30));
    assert_eq!(config.custom, Duration::from_secs(30));
}

#[test]
fn test_timeout_config_patient() {
    let config = TimeoutConfig::patient();
    assert_eq!(config.confirm, Duration::from_secs(60));
    assert_eq!(config.prompt, Duration::from_secs(60));
    assert_eq!(config.select, Duration::from_secs(60));
    assert_eq!(config.custom, Duration::from_secs(60));
}

#[test]
fn test_timeout_config_extended() {
    let config = TimeoutConfig::extended();
    assert_eq!(config.confirm, Duration::from_secs(300));
    assert_eq!(config.prompt, Duration::from_secs(300));
    assert_eq!(config.select, Duration::from_secs(300));
    assert_eq!(config.custom, Duration::from_secs(300));
}

#[test]
fn test_timeout_config_default() {
    let config = TimeoutConfig::default();
    assert_eq!(config.confirm, Duration::from_secs(30)); // Same as normal
}

// =============================================================================
// Error Message Tests
// =============================================================================

#[test]
fn test_bidir_error_messages() {
    assert_eq!(
        bidir_error_message(&BidirError::NotSupported),
        "Bidirectional communication not supported by this transport"
    );

    assert_eq!(
        bidir_error_message(&BidirError::Timeout(5000)),
        "Request timed out waiting for response (after 5000ms)"
    );

    assert_eq!(
        bidir_error_message(&BidirError::Cancelled),
        "Request was cancelled by user"
    );

    assert_eq!(
        bidir_error_message(&BidirError::TypeMismatch {
            expected: "Confirmed".into(),
            got: "Text".into()
        }),
        "Type mismatch: expected Confirmed, got Text"
    );

    assert_eq!(
        bidir_error_message(&BidirError::Serialization("parse error".into())),
        "Serialization error: parse error"
    );

    assert_eq!(
        bidir_error_message(&BidirError::Transport("connection lost".into())),
        "Transport error: connection lost"
    );

    assert_eq!(
        bidir_error_message(&BidirError::UnknownRequest),
        "Unknown request ID (may have already been handled)"
    );

    assert_eq!(
        bidir_error_message(&BidirError::ChannelClosed),
        "Response channel closed before response received"
    );
}

// =============================================================================
// SelectOption Tests
// =============================================================================

#[test]
fn test_select_option_new() {
    let opt = SelectOption::new("value", "Label");
    assert_eq!(opt.value, "value");
    assert_eq!(opt.label, "Label");
    assert!(opt.description.is_none());
}

#[test]
fn test_select_option_with_description() {
    let opt = SelectOption::new("key", "Display").with_description("A helpful description");
    assert_eq!(opt.value, "key");
    assert_eq!(opt.label, "Display");
    assert_eq!(opt.description, Some("A helpful description".into()));
}

#[test]
fn test_select_option_serialization() {
    let opt = SelectOption::new("prod", "Production").with_description("Production environment");

    let json = serde_json::to_value(&opt).unwrap();
    assert_eq!(json["value"], "prod");
    assert_eq!(json["label"], "Production");
    assert_eq!(json["description"], "Production environment");
}

#[test]
fn test_select_option_without_description_serialization() {
    let opt = SelectOption::new("dev", "Development");

    let json = serde_json::to_value(&opt).unwrap();
    assert_eq!(json["value"], "dev");
    assert_eq!(json["label"], "Development");
    // description should be absent due to skip_serializing_if
    assert!(json.get("description").is_none());
}

// =============================================================================
// StandardRequest/StandardResponse Serialization Tests
// =============================================================================

#[test]
fn test_standard_request_confirm_serialization() {
    let req: StandardRequest = StandardRequest::Confirm {
        message: "Continue?".into(),
        default: Some(true),
    };

    let json = serde_json::to_value(&req).unwrap();
    assert_eq!(json["type"], "confirm");
    assert_eq!(json["message"], "Continue?");
    assert_eq!(json["default"], true);

    // Roundtrip
    let decoded: StandardRequest = serde_json::from_value(json).unwrap();
    assert_eq!(req, decoded);
}

#[test]
fn test_standard_request_prompt_serialization() {
    let req: StandardRequest = StandardRequest::Prompt {
        message: "Enter name:".into(),
        default: Some(serde_json::Value::String("John".into())),
        placeholder: Some("Type here...".into()),
    };

    let json = serde_json::to_value(&req).unwrap();
    assert_eq!(json["type"], "prompt");
    assert_eq!(json["message"], "Enter name:");
    assert_eq!(json["default"], "John");
    assert_eq!(json["placeholder"], "Type here...");
}

#[test]
fn test_standard_request_select_serialization() {
    let req: StandardRequest = StandardRequest::Select {
        message: "Choose:".into(),
        options: vec![
            SelectOption::new("a", "Option A"),
            SelectOption::new("b", "Option B"),
        ],
        multi_select: true,
    };

    let json = serde_json::to_value(&req).unwrap();
    assert_eq!(json["type"], "select");
    assert_eq!(json["message"], "Choose:");
    assert_eq!(json["multi_select"], true);
    assert_eq!(json["options"].as_array().unwrap().len(), 2);
}

#[test]
fn test_standard_response_confirmed_serialization() {
    let resp: StandardResponse = StandardResponse::Confirmed { value: true };
    let json = serde_json::to_value(&resp).unwrap();
    // Internally tagged: { "type": "confirmed", "value": true }
    assert_eq!(json["type"], "confirmed");
    assert_eq!(json["value"], true);

    let decoded: StandardResponse = serde_json::from_value(json).unwrap();
    assert_eq!(resp, decoded);
}

#[test]
fn test_standard_response_text_serialization() {
    let resp: StandardResponse = StandardResponse::Text {
        value: serde_json::Value::String("Hello".into()),
    };
    let json = serde_json::to_value(&resp).unwrap();
    // Internally tagged: { "type": "text", "value": "Hello" }
    assert_eq!(json["type"], "text");
    assert_eq!(json["value"], "Hello");
}

#[test]
fn test_standard_response_selected_serialization() {
    let resp: StandardResponse = StandardResponse::Selected {
        values: vec![
            serde_json::Value::String("a".into()),
            serde_json::Value::String("b".into()),
        ],
    };
    let json = serde_json::to_value(&resp).unwrap();
    // Internally tagged: { "type": "selected", "values": ["a", "b"] }
    assert_eq!(json["type"], "selected");
    let values = json["values"].as_array().unwrap();
    assert_eq!(values.len(), 2);
    assert_eq!(values[0], "a");
    assert_eq!(values[1], "b");
}

#[test]
fn test_standard_response_cancelled_serialization() {
    let resp: StandardResponse = StandardResponse::Cancelled;
    let json = serde_json::to_value(&resp).unwrap();
    // Internally tagged unit variant: { "type": "cancelled" }
    assert_eq!(json["type"], "cancelled");

    let decoded: StandardResponse = serde_json::from_value(json).unwrap();
    assert_eq!(resp, decoded);
}

// =============================================================================
// Custom Type Tests
// =============================================================================

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
enum TestRequest {
    Ping { value: i32 },
    Echo { message: String },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
enum TestResponse {
    Pong { value: i32 },
    Echoed { message: String },
}

#[tokio::test]
async fn test_custom_types_basic_flow() {
    let (tx, mut rx) = mpsc::channel::<PlexusStreamItem>(32);
    let channel: Arc<BidirChannel<TestRequest, TestResponse>> =
        Arc::new(BidirChannel::new_direct(tx, true, vec![], "hash".into()));

    let channel_clone = channel.clone();
    let handle = tokio::spawn(async move {
        channel_clone.request(TestRequest::Ping { value: 42 }).await
    });

    if let Some(PlexusStreamItem::Request {
        request_id,
        request_data,
        ..
    }) = rx.recv().await
    {
        assert_eq!(request_data["type"], "ping");
        assert_eq!(request_data["value"], 42);

        channel
            .handle_response(
                request_id,
                serde_json::to_value(&TestResponse::Pong { value: 42 }).unwrap(),
            )
            .unwrap();
    }

    let result = handle.await.unwrap().unwrap();
    assert_eq!(result, TestResponse::Pong { value: 42 });
}

#[tokio::test]
async fn test_custom_types_echo() {
    let (tx, mut rx) = mpsc::channel(32);
    let channel: Arc<BidirChannel<TestRequest, TestResponse>> =
        Arc::new(BidirChannel::new_direct(tx, true, vec![], "hash".into()));

    let channel_clone = channel.clone();
    let handle = tokio::spawn(async move {
        channel_clone
            .request(TestRequest::Echo {
                message: "Hello".into(),
            })
            .await
    });

    if let Some(PlexusStreamItem::Request { request_id, .. }) = rx.recv().await {
        channel
            .handle_response(
                request_id,
                serde_json::to_value(&TestResponse::Echoed {
                    message: "Hello".into(),
                })
                .unwrap(),
            )
            .unwrap();
    }

    let result = handle.await.unwrap().unwrap();
    assert_eq!(
        result,
        TestResponse::Echoed {
            message: "Hello".into()
        }
    );
}

// =============================================================================
// PlexusStreamItem Request Tests
// =============================================================================

#[test]
fn test_plexus_stream_item_request_creation() {
    let item = PlexusStreamItem::request(
        "req-123".into(),
        serde_json::json!({"key": "value"}),
        5000,
    );

    match item {
        PlexusStreamItem::Request {
            request_id,
            request_data,
            timeout_ms,
        } => {
            assert_eq!(request_id, "req-123");
            assert_eq!(request_data["key"], "value");
            assert_eq!(timeout_ms, 5000);
        }
        _ => panic!("Expected Request variant"),
    }
}

#[test]
fn test_plexus_stream_item_request_serialization() {
    let item = PlexusStreamItem::request(
        "uuid-here".into(),
        serde_json::json!({"type": "confirm", "message": "Test?"}),
        30000,
    );

    let json = serde_json::to_value(&item).unwrap();
    assert_eq!(json["type"], "request");
    // Request fields are camelCase for JavaScript/TypeScript compatibility
    assert_eq!(json["requestId"], "uuid-here");
    assert_eq!(json["timeoutMs"], 30000);
    assert_eq!(json["requestData"]["type"], "confirm");
    assert_eq!(json["requestData"]["message"], "Test?");
}

#[test]
fn test_plexus_stream_item_request_no_metadata() {
    let item = PlexusStreamItem::request("id".into(), serde_json::json!({}), 1000);

    // Request items don't have metadata
    assert!(item.metadata().is_none());
}

// =============================================================================
// BidirError Tests
// =============================================================================

#[test]
fn test_bidir_error_display() {
    assert_eq!(
        BidirError::NotSupported.to_string(),
        "Bidirectional communication not supported by this transport"
    );

    assert_eq!(
        BidirError::Timeout(30000).to_string(),
        "Request timed out after 30000ms"
    );

    assert_eq!(
        BidirError::Cancelled.to_string(),
        "Request was cancelled by client"
    );

    assert_eq!(
        BidirError::TypeMismatch {
            expected: "A".into(),
            got: "B".into()
        }
        .to_string(),
        "Type mismatch: expected A, got B"
    );

    assert_eq!(
        BidirError::Serialization("error".into()).to_string(),
        "Serialization error: error"
    );

    assert_eq!(
        BidirError::Transport("failed".into()).to_string(),
        "Transport error: failed"
    );

    assert_eq!(
        BidirError::UnknownRequest.to_string(),
        "Unknown request ID"
    );

    assert_eq!(
        BidirError::ChannelClosed.to_string(),
        "Response channel closed"
    );
}

#[test]
fn test_bidir_error_clone() {
    let err = BidirError::Timeout(5000);
    let cloned = err.clone();
    assert!(matches!(cloned, BidirError::Timeout(5000)));
}