jsonrpc-debugger 0.1.9

A terminal-based JSON-RPC debugger with interception capabilities
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
use ratatui::widgets::TableState;
use std::collections::HashMap;
use tokio::sync::{mpsc, oneshot};

#[derive(Debug, Clone)]
pub struct JsonRpcMessage {
    pub id: Option<serde_json::Value>,
    pub method: Option<String>,
    pub params: Option<serde_json::Value>,
    pub result: Option<serde_json::Value>,
    pub error: Option<serde_json::Value>,
    pub timestamp: std::time::SystemTime,
    pub direction: MessageDirection,
    pub transport: TransportType,
    pub headers: Option<HashMap<String, String>>,
}

#[derive(Debug, Clone)]
pub struct JsonRpcExchange {
    pub id: Option<serde_json::Value>,
    pub method: Option<String>,
    pub request: Option<JsonRpcMessage>,
    pub response: Option<JsonRpcMessage>,
    #[allow(dead_code)] // Used in UI for duration calculation
    pub timestamp: std::time::SystemTime,
    pub transport: TransportType,
}

#[derive(Debug, Clone)]
pub enum MessageDirection {
    Request,
    Response,
}

#[derive(Debug, Clone)]
pub enum TransportType {
    Http,
    #[allow(dead_code)] // Used in tests and UI display
    WebSocket,
}

#[derive(Debug, Clone, PartialEq)]
pub enum InputMode {
    Normal,
    EditingTarget,
    FilteringRequests,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Focus {
    MessageList,
    RequestSection,
    ResponseSection,
    StatusHeader,
}

#[derive(Debug, Clone, PartialEq)]
pub enum AppMode {
    Normal,       // Regular proxy mode
    Paused,       // All requests paused
    Intercepting, // Inspecting a specific request
}

#[derive(Debug)]
pub enum ProxyDecision {
    Allow(Option<serde_json::Value>, Option<HashMap<String, String>>), // Allow with optional modified JSON and headers
    Block,                                                             // Block the request
    Complete(serde_json::Value), // Complete with custom response
}

#[allow(dead_code)]
pub struct PendingRequest {
    pub id: String,
    pub original_request: JsonRpcMessage,
    pub modified_request: Option<String>, // JSON string for editing
    pub modified_headers: Option<HashMap<String, String>>, // Modified headers
    pub decision_sender: oneshot::Sender<ProxyDecision>,
}

#[allow(dead_code)]
pub struct App {
    pub exchanges: Vec<JsonRpcExchange>,
    pub selected_exchange: usize,
    pub filter_text: String,
    pub table_state: TableState,
    pub details_scroll: usize,
    pub request_details_scroll: usize,
    pub response_details_scroll: usize,
    pub details_tab: usize,
    pub request_details_tab: usize,
    pub response_details_tab: usize,
    pub intercept_details_scroll: usize, // New field for intercept details scrolling
    pub proxy_config: ProxyConfig,
    pub is_running: bool,
    pub message_receiver: Option<mpsc::UnboundedReceiver<JsonRpcMessage>>,
    pub input_mode: InputMode,
    pub input_buffer: String,
    pub app_mode: AppMode,                     // New field
    pub pending_requests: Vec<PendingRequest>, // New field
    pub selected_pending: usize,               // New field
    pub request_editor_buffer: String,         // New field
    pub focus: Focus,                          // New field for tracking which element is active
    pub request_tab: usize,                    // 0 = Headers, 1 = Body
    pub response_tab: usize,                   // 0 = Headers, 1 = Body
}

#[derive(Debug)]
#[allow(dead_code)]
pub struct ProxyConfig {
    pub listen_port: u16,
    pub target_url: String,
    pub transport: TransportType,
}

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

#[allow(dead_code)]
impl App {
    pub fn new() -> Self {
        let mut table_state = TableState::default();
        table_state.select(Some(0));

        Self {
            exchanges: Vec::new(),
            selected_exchange: 0,
            filter_text: String::new(),
            table_state,
            details_scroll: 0,
            request_details_scroll: 0,
            response_details_scroll: 0,
            details_tab: 0,
            request_details_tab: 0,
            response_details_tab: 0,
            intercept_details_scroll: 0,
            proxy_config: ProxyConfig {
                listen_port: 8080,
                target_url: "".to_string(),
                transport: TransportType::Http,
            },
            is_running: true,
            message_receiver: None,
            input_mode: InputMode::Normal,
            input_buffer: String::new(),
            app_mode: AppMode::Normal,
            pending_requests: Vec::new(),
            selected_pending: 0,
            request_editor_buffer: String::new(),
            focus: Focus::MessageList,
            request_tab: 1,  // Body selected by default
            response_tab: 1, // Body selected by default
        }
    }

    pub fn new_with_receiver(receiver: mpsc::UnboundedReceiver<JsonRpcMessage>) -> Self {
        let mut table_state = TableState::default();
        table_state.select(Some(0));

        Self {
            exchanges: Vec::new(),
            selected_exchange: 0,
            filter_text: String::new(),
            table_state,
            details_scroll: 0,
            request_details_scroll: 0,
            response_details_scroll: 0,
            details_tab: 0,
            request_details_tab: 0,
            response_details_tab: 0,
            intercept_details_scroll: 0,
            proxy_config: ProxyConfig {
                listen_port: 8080,
                target_url: "".to_string(),
                transport: TransportType::Http,
            },
            is_running: true,
            message_receiver: Some(receiver),
            input_mode: InputMode::Normal,
            input_buffer: String::new(),
            app_mode: AppMode::Normal,
            pending_requests: Vec::new(),
            selected_pending: 0,
            request_editor_buffer: String::new(),
            focus: Focus::MessageList,
            request_tab: 1,  // Body selected by default
            response_tab: 1, // Body selected by default
        }
    }

    pub fn check_for_new_messages(&mut self) {
        if let Some(receiver) = &mut self.message_receiver {
            let mut new_messages = Vec::new();
            while let Ok(message) = receiver.try_recv() {
                new_messages.push(message);
            }
            for message in new_messages {
                self.add_message(message);
            }
        }
    }

    pub fn add_message(&mut self, mut message: JsonRpcMessage) {
        // Sanitize message content to prevent UI corruption
        if let Some(ref mut error) = message.error {
            if let Some(data) = error.get_mut("data") {
                if let Some(data_str) = data.as_str() {
                    let sanitized = data_str
                        .chars()
                        .filter(|c| c.is_ascii() && (!c.is_control() || *c == '\n' || *c == '\t'))
                        .take(500)
                        .collect::<String>();
                    *data = serde_json::Value::String(sanitized);
                }
            }
        }

        match message.direction {
            MessageDirection::Request => {
                // Create a new exchange for the request
                let exchange = JsonRpcExchange {
                    id: message.id.clone(),
                    method: message.method.clone(),
                    request: Some(message.clone()),
                    response: None,
                    timestamp: message.timestamp,
                    transport: message.transport.clone(),
                };
                self.exchanges.push(exchange);
            }
            MessageDirection::Response => {
                // Find matching request by ID and add response
                if let Some(exchange) = self
                    .exchanges
                    .iter_mut()
                    .rev()
                    .find(|e| e.id == message.id && e.response.is_none())
                {
                    exchange.response = Some(message);
                } else {
                    // No matching request found, create exchange with just response
                    let exchange = JsonRpcExchange {
                        id: message.id.clone(),
                        method: None,
                        request: None,
                        response: Some(message.clone()),
                        timestamp: message.timestamp,
                        transport: message.transport.clone(),
                    };
                    self.exchanges.push(exchange);
                }
            }
        }
    }

    pub fn get_selected_exchange(&self) -> Option<&JsonRpcExchange> {
        self.exchanges.get(self.selected_exchange)
    }

    pub fn select_next(&mut self) {
        if !self.exchanges.is_empty() {
            self.selected_exchange = (self.selected_exchange + 1) % self.exchanges.len();
            self.table_state.select(Some(self.selected_exchange));
            self.reset_details_scroll();
            self.request_details_scroll = 0;
            self.response_details_scroll = 0;
            self.details_tab = 0;
            self.request_details_tab = 0;
            self.response_details_tab = 0;
        }
    }

    pub fn select_previous(&mut self) {
        if !self.exchanges.is_empty() {
            self.selected_exchange = if self.selected_exchange == 0 {
                self.exchanges.len() - 1
            } else {
                self.selected_exchange - 1
            };
            self.table_state.select(Some(self.selected_exchange));
            self.reset_details_scroll();
            self.request_details_scroll = 0;
            self.response_details_scroll = 0;
            self.details_tab = 0;
            self.request_details_tab = 0;
            self.response_details_tab = 0;
        }
    }

    pub fn toggle_proxy(&mut self) {
        self.is_running = !self.is_running;
    }

    pub fn scroll_details_up(&mut self) {
        if self.details_scroll > 0 {
            self.details_scroll -= 1;
        }
    }

    pub fn scroll_details_down(&mut self, max_lines: usize, visible_lines: usize) {
        if max_lines > visible_lines && self.details_scroll < max_lines - visible_lines {
            self.details_scroll += 1;
        }
    }

    pub fn reset_details_scroll(&mut self) {
        self.details_scroll = 0;
    }

    // Intercept details scrolling methods
    pub fn scroll_intercept_details_up(&mut self) {
        if self.intercept_details_scroll > 0 {
            self.intercept_details_scroll -= 1;
        }
    }

    pub fn scroll_intercept_details_down(&mut self, max_lines: usize, visible_lines: usize) {
        if max_lines > visible_lines && self.intercept_details_scroll < max_lines - visible_lines {
            self.intercept_details_scroll += 1;
        }
    }

    pub fn reset_intercept_details_scroll(&mut self) {
        self.intercept_details_scroll = 0;
    }

    pub fn page_down_intercept_details(&mut self) {
        let page_size = 10; // Half page
        self.intercept_details_scroll += page_size;
    }

    pub fn page_up_intercept_details(&mut self) {
        let page_size = 10; // Half page
        self.intercept_details_scroll = self.intercept_details_scroll.saturating_sub(page_size);
    }

    pub fn goto_top_intercept_details(&mut self) {
        self.intercept_details_scroll = 0;
    }

    pub fn goto_bottom_intercept_details(&mut self, max_lines: usize, visible_lines: usize) {
        if max_lines > visible_lines {
            self.intercept_details_scroll = max_lines - visible_lines;
        }
    }

    // Enhanced details scrolling with vim-style page jumps
    pub fn page_down_details(&mut self, visible_lines: usize) {
        let page_size = visible_lines / 2; // Half page
        self.details_scroll += page_size;
    }

    pub fn page_up_details(&mut self) {
        let page_size = 10; // Half page
        self.details_scroll = self.details_scroll.saturating_sub(page_size);
    }

    pub fn goto_top_details(&mut self) {
        self.details_scroll = 0;
    }

    pub fn goto_bottom_details(&mut self, max_lines: usize, visible_lines: usize) {
        if max_lines > visible_lines {
            self.details_scroll = max_lines - visible_lines;
        }
    }

    pub fn switch_focus(&mut self) {
        self.focus = match self.focus {
            Focus::MessageList => Focus::RequestSection,
            Focus::RequestSection => Focus::ResponseSection,
            Focus::ResponseSection => Focus::StatusHeader,
            Focus::StatusHeader => Focus::MessageList,
        };
        self.reset_details_scroll();
        self.request_details_scroll = 0;
        self.response_details_scroll = 0;
    }

    pub fn switch_focus_reverse(&mut self) {
        self.focus = match self.focus {
            Focus::MessageList => Focus::StatusHeader,
            Focus::RequestSection => Focus::MessageList,
            Focus::ResponseSection => Focus::RequestSection,
            Focus::StatusHeader => Focus::ResponseSection,
        };
        self.reset_details_scroll();
        self.request_details_scroll = 0;
        self.response_details_scroll = 0;
    }

    pub fn is_message_list_focused(&self) -> bool {
        matches!(self.focus, Focus::MessageList)
    }

    pub fn is_request_section_focused(&self) -> bool {
        matches!(self.focus, Focus::RequestSection)
    }

    pub fn is_response_section_focused(&self) -> bool {
        matches!(self.focus, Focus::ResponseSection)
    }

    pub fn is_status_focused(&self) -> bool {
        matches!(self.focus, Focus::StatusHeader)
    }

    pub fn next_request_tab(&mut self) {
        self.request_tab = 1 - self.request_tab; // Toggle between 0 and 1
        self.reset_details_scroll();
    }

    pub fn previous_request_tab(&mut self) {
        self.request_tab = 1 - self.request_tab; // Toggle between 0 and 1
        self.reset_details_scroll();
    }

    pub fn next_response_tab(&mut self) {
        self.response_tab = 1 - self.response_tab; // Toggle between 0 and 1
        self.reset_details_scroll();
    }

    pub fn previous_response_tab(&mut self) {
        self.response_tab = 1 - self.response_tab; // Toggle between 0 and 1
        self.reset_details_scroll();
    }

    // Filtering requests methods
    pub fn start_filtering_requests(&mut self) {
        self.input_mode = InputMode::FilteringRequests;
        self.input_buffer.clear();
    }

    pub fn cancel_filtering(&mut self) {
        self.input_mode = InputMode::Normal;
        self.input_buffer.clear();
    }

    pub fn apply_filter(&mut self) {
        self.filter_text = self.input_buffer.clone();
        self.input_mode = InputMode::Normal;
        self.input_buffer.clear();
    }

    // Get content lines for proper scrolling calculations
    // Target editing methods
    pub fn start_editing_target(&mut self) {
        self.input_mode = InputMode::EditingTarget;
        self.input_buffer = self.proxy_config.target_url.clone();
    }

    pub fn cancel_editing(&mut self) {
        self.input_mode = InputMode::Normal;
        self.input_buffer.clear();
    }

    pub fn confirm_target_edit(&mut self) {
        if !self.input_buffer.trim().is_empty() {
            self.proxy_config.target_url = self.input_buffer.trim().to_string();
        }
        self.input_mode = InputMode::Normal;
        self.input_buffer.clear();
    }

    pub fn handle_input_char(&mut self, c: char) {
        if self.input_mode == InputMode::EditingTarget
            || self.input_mode == InputMode::FilteringRequests
        {
            self.input_buffer.push(c);
        }
    }

    pub fn handle_backspace(&mut self) {
        if self.input_mode == InputMode::EditingTarget
            || self.input_mode == InputMode::FilteringRequests
        {
            self.input_buffer.pop();
        }
    }

    pub fn get_details_content_lines(&self) -> usize {
        if let Some(exchange) = self.get_selected_exchange() {
            let mut line_count = 1; // Transport line

            if exchange.method.is_some() {
                line_count += 1;
            }
            if exchange.id.is_some() {
                line_count += 1;
            }

            // Request section
            line_count += 1; // Blank line before section
            line_count += 1; // Section header
            line_count += 1; // Tabs line

            if let Some(request) = &exchange.request {
                match self.request_details_tab {
                    0 => match &request.headers {
                        Some(headers) if !headers.is_empty() => {
                            line_count += headers.len();
                        }
                        Some(_) | None => {
                            line_count += 1;
                        }
                    },
                    _ => {
                        let mut request_json = serde_json::Map::new();
                        request_json.insert(
                            "jsonrpc".to_string(),
                            serde_json::Value::String("2.0".to_string()),
                        );
                        if let Some(id) = &request.id {
                            request_json.insert("id".to_string(), id.clone());
                        }
                        if let Some(method) = &request.method {
                            request_json.insert(
                                "method".to_string(),
                                serde_json::Value::String(method.clone()),
                            );
                        }
                        if let Some(params) = &request.params {
                            request_json.insert("params".to_string(), params.clone());
                        }

                        if let Ok(json_str) =
                            serde_json::to_string_pretty(&serde_json::Value::Object(request_json))
                        {
                            line_count += json_str.lines().count();
                        }
                    }
                }
            } else {
                line_count += 1;
            }

            // Response section
            line_count += 1; // Blank line before section
            line_count += 1; // Section header
            line_count += 1; // Tabs line

            if let Some(response) = &exchange.response {
                match self.response_details_tab {
                    0 => match &response.headers {
                        Some(headers) if !headers.is_empty() => {
                            line_count += headers.len();
                        }
                        Some(_) | None => {
                            line_count += 1;
                        }
                    },
                    _ => {
                        let mut response_json = serde_json::Map::new();
                        response_json.insert(
                            "jsonrpc".to_string(),
                            serde_json::Value::String("2.0".to_string()),
                        );
                        if let Some(id) = &response.id {
                            response_json.insert("id".to_string(), id.clone());
                        }
                        if let Some(result) = &response.result {
                            response_json.insert("result".to_string(), result.clone());
                        }
                        if let Some(error) = &response.error {
                            response_json.insert("error".to_string(), error.clone());
                        }

                        if let Ok(json_str) =
                            serde_json::to_string_pretty(&serde_json::Value::Object(response_json))
                        {
                            line_count += json_str.lines().count();
                        }
                    }
                }
            } else {
                line_count += 1;
            }

            line_count
        } else {
            1
        }
    }

    pub fn get_request_details_content_lines(&self) -> usize {
        if let Some(exchange) = self.get_selected_exchange() {
            let mut line_count = 0;

            // Basic exchange info
            line_count += 1; // Transport line

            if exchange.method.is_some() {
                line_count += 1;
            }
            if exchange.id.is_some() {
                line_count += 1;
            }

            // Request section
            line_count += 1; // Blank line before section
            line_count += 1; // Section header
            line_count += 1; // Tabs line

            if let Some(request) = &exchange.request {
                match self.request_details_tab {
                    0 => match &request.headers {
                        Some(headers) if !headers.is_empty() => {
                            line_count += headers.len();
                        }
                        Some(_) | None => {
                            line_count += 1;
                        }
                    },
                    _ => {
                        let mut request_json = serde_json::Map::new();
                        request_json.insert(
                            "jsonrpc".to_string(),
                            serde_json::Value::String("2.0".to_string()),
                        );
                        if let Some(id) = &request.id {
                            request_json.insert("id".to_string(), id.clone());
                        }
                        if let Some(method) = &request.method {
                            request_json.insert(
                                "method".to_string(),
                                serde_json::Value::String(method.clone()),
                            );
                        }
                        if let Some(params) = &request.params {
                            request_json.insert("params".to_string(), params.clone());
                        }

                        if let Ok(json_str) =
                            serde_json::to_string_pretty(&serde_json::Value::Object(request_json))
                        {
                            line_count += json_str.lines().count();
                        }
                    }
                }
            } else {
                line_count += 1;
            }

            line_count
        } else {
            1
        }
    }

    pub fn get_response_details_content_lines(&self) -> usize {
        if let Some(exchange) = self.get_selected_exchange() {
            let mut line_count = 0;

            // Response section
            line_count += 1; // Section header
            line_count += 1; // Tabs line

            if let Some(response) = &exchange.response {
                match self.response_details_tab {
                    0 => match &response.headers {
                        Some(headers) if !headers.is_empty() => {
                            line_count += headers.len();
                        }
                        Some(_) | None => {
                            line_count += 1;
                        }
                    },
                    _ => {
                        let mut response_json = serde_json::Map::new();
                        response_json.insert(
                            "jsonrpc".to_string(),
                            serde_json::Value::String("2.0".to_string()),
                        );
                        if let Some(id) = &response.id {
                            response_json.insert("id".to_string(), id.clone());
                        }
                        if let Some(result) = &response.result {
                            response_json.insert("result".to_string(), result.clone());
                        }
                        if let Some(error) = &response.error {
                            response_json.insert("error".to_string(), error.clone());
                        }

                        if let Ok(json_str) =
                            serde_json::to_string_pretty(&serde_json::Value::Object(response_json))
                        {
                            line_count += json_str.lines().count();
                        }
                    }
                }
            } else {
                line_count += 1;
            }

            line_count
        } else {
            1
        }
    }

    // Pause/Intercept functionality
    pub fn toggle_pause_mode(&mut self) {
        self.app_mode = match self.app_mode {
            AppMode::Normal => AppMode::Paused,
            AppMode::Paused => AppMode::Normal,
            AppMode::Intercepting => AppMode::Normal,
        };
    }

    pub fn select_next_pending(&mut self) {
        if !self.pending_requests.is_empty() {
            self.selected_pending = (self.selected_pending + 1) % self.pending_requests.len();
            self.reset_intercept_details_scroll();
        }
    }

    pub fn select_previous_pending(&mut self) {
        if !self.pending_requests.is_empty() {
            self.selected_pending = if self.selected_pending == 0 {
                self.pending_requests.len() - 1
            } else {
                self.selected_pending - 1
            };
            self.reset_intercept_details_scroll();
        }
    }

    pub fn get_selected_pending(&self) -> Option<&PendingRequest> {
        self.pending_requests.get(self.selected_pending)
    }

    pub fn allow_selected_request(&mut self) {
        if self.selected_pending < self.pending_requests.len() {
            let pending = self.pending_requests.remove(self.selected_pending);
            if self.selected_pending > 0 && self.selected_pending >= self.pending_requests.len() {
                self.selected_pending -= 1;
            }

            // Send decision to proxy
            let decision = if let Some(ref modified_json) = pending.modified_request {
                if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(modified_json) {
                    ProxyDecision::Allow(Some(parsed), pending.modified_headers.clone())
                } else {
                    ProxyDecision::Allow(None, pending.modified_headers.clone())
                    // Fallback to original if modified JSON is invalid
                }
            } else {
                ProxyDecision::Allow(None, pending.modified_headers.clone()) // Use original request
            };

            let _ = pending.decision_sender.send(decision);
        }
    }

    pub fn block_selected_request(&mut self) {
        if self.selected_pending < self.pending_requests.len() {
            let pending = self.pending_requests.remove(self.selected_pending);
            if self.selected_pending > 0 && self.selected_pending >= self.pending_requests.len() {
                self.selected_pending -= 1;
            }

            // Send block decision to proxy
            let _ = pending.decision_sender.send(ProxyDecision::Block);
        }
    }

    pub fn resume_all_requests(&mut self) {
        for pending in self.pending_requests.drain(..) {
            let _ = pending
                .decision_sender
                .send(ProxyDecision::Allow(None, None));
        }
        self.selected_pending = 0;
        self.app_mode = AppMode::Normal;
    }

    pub fn get_pending_request_json(&self) -> Option<String> {
        if let Some(pending) = self.get_selected_pending() {
            // Get the original request JSON and format it nicely
            let json_value = serde_json::json!({
                "jsonrpc": "2.0",
                "method": pending.original_request.method,
                "params": pending.original_request.params,
                "id": pending.original_request.id
            });

            // Pretty print the JSON for editing
            serde_json::to_string_pretty(&json_value).ok()
        } else {
            None
        }
    }

    pub fn apply_edited_json(&mut self, edited_json: String) -> Result<(), String> {
        if self.selected_pending >= self.pending_requests.len() {
            return Err("No pending request selected".to_string());
        }

        // Parse the edited JSON
        let parsed: serde_json::Value =
            serde_json::from_str(&edited_json).map_err(|e| format!("Invalid JSON: {}", e))?;

        // Validate it's a proper JSON-RPC request
        if parsed.get("jsonrpc") != Some(&serde_json::Value::String("2.0".to_string())) {
            return Err("Missing or invalid 'jsonrpc' field".to_string());
        }

        if parsed.get("method").is_none() {
            return Err("Missing 'method' field".to_string());
        }

        // Store the modified request
        self.pending_requests[self.selected_pending].modified_request = Some(edited_json);

        Ok(())
    }

    pub fn get_pending_request_headers(&self) -> Option<String> {
        if let Some(pending) = self.get_selected_pending() {
            // Get headers (modified if available, otherwise original)
            let headers = pending
                .modified_headers
                .as_ref()
                .or(pending.original_request.headers.as_ref());

            if let Some(headers) = headers {
                // Format headers as key: value pairs for editing
                let mut header_lines = Vec::new();
                for (key, value) in headers {
                    header_lines.push(format!("{}: {}", key, value));
                }
                Some(header_lines.join("\n"))
            } else {
                Some(
                    "# No headers\n# Add headers in the format:\n# header-name: header-value"
                        .to_string(),
                )
            }
        } else {
            None
        }
    }

    pub fn apply_edited_headers(&mut self, edited_headers: String) -> Result<(), String> {
        if self.selected_pending >= self.pending_requests.len() {
            return Err("No pending request selected".to_string());
        }

        let mut headers = HashMap::new();

        for line in edited_headers.lines() {
            let line = line.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            // Parse header line (key: value)
            if let Some(colon_pos) = line.find(':') {
                let key = line[..colon_pos].trim().to_string();
                let value = line[colon_pos + 1..].trim().to_string();

                if !key.is_empty() {
                    headers.insert(key, value);
                }
            } else {
                return Err(format!(
                    "Invalid header format: '{}'. Use 'key: value' format.",
                    line
                ));
            }
        }

        // Store the modified headers
        self.pending_requests[self.selected_pending].modified_headers = Some(headers);

        Ok(())
    }

    pub fn get_pending_response_template(&self) -> Option<String> {
        if let Some(pending) = self.get_selected_pending() {
            // Create a template JSON-RPC response with simple string result
            let response_template = serde_json::json!({
                "jsonrpc": "2.0",
                "id": pending.original_request.id,
                "result": "custom response"
            });

            // Pretty print the JSON for editing
            serde_json::to_string_pretty(&response_template).ok()
        } else {
            None
        }
    }

    pub fn complete_selected_request(&mut self, response_json: String) -> Result<(), String> {
        if self.selected_pending >= self.pending_requests.len() {
            return Err("No pending request selected".to_string());
        }

        // Parse the response JSON
        let parsed: serde_json::Value =
            serde_json::from_str(&response_json).map_err(|e| format!("Invalid JSON: {}", e))?;

        // Validate it's a proper JSON-RPC response
        if parsed.get("jsonrpc") != Some(&serde_json::Value::String("2.0".to_string())) {
            return Err("Missing or invalid 'jsonrpc' field".to_string());
        }

        if parsed.get("id").is_none() {
            return Err("Missing 'id' field".to_string());
        }

        // Must have either result or error, but not both
        let has_result = parsed.get("result").is_some();
        let has_error = parsed.get("error").is_some();

        if !has_result && !has_error {
            return Err("Response must have either 'result' or 'error' field".to_string());
        }

        if has_result && has_error {
            return Err("Response cannot have both 'result' and 'error' fields".to_string());
        }

        // Remove the pending request and send the completion decision
        let pending = self.pending_requests.remove(self.selected_pending);
        if self.selected_pending > 0 && self.selected_pending >= self.pending_requests.len() {
            self.selected_pending -= 1;
        }

        let _ = pending
            .decision_sender
            .send(ProxyDecision::Complete(parsed));

        Ok(())
    }

    pub async fn send_new_request(&self, request_json: String) -> Result<(), String> {
        // Parse the request JSON
        let parsed: serde_json::Value =
            serde_json::from_str(&request_json).map_err(|e| format!("Invalid JSON: {}", e))?;

        // Validate it's a proper JSON-RPC request
        if parsed.get("jsonrpc") != Some(&serde_json::Value::String("2.0".to_string())) {
            return Err("Missing or invalid 'jsonrpc' field".to_string());
        }

        if parsed.get("method").is_none() {
            return Err("Missing 'method' field".to_string());
        }

        // Check if target URL is empty
        if self.proxy_config.target_url.trim().is_empty() {
            return Err("Target URL is not set. Press 't' to set a target URL first.".to_string());
        }

        let client = reqwest::Client::new();

        // If we're in paused mode, send directly to target to avoid interception
        // Otherwise, send through proxy for normal logging
        let url = if matches!(self.app_mode, AppMode::Paused | AppMode::Intercepting) {
            &self.proxy_config.target_url
        } else {
            // Send through proxy for normal logging
            &format!("http://localhost:{}", self.proxy_config.listen_port)
        };

        let response = client
            .post(url)
            .header("Content-Type", "application/json")
            .body(request_json)
            .send()
            .await
            .map_err(|e| format!("Failed to send request: {}", e))?;

        if !response.status().is_success() {
            return Err(format!("Request failed with status: {}", response.status()));
        }

        Ok(())
    }
}